import json
def load_text_blocks(filepath):
"""
Loads text blocks from a JSON file.
Args:
filepath (str): The path to the JSON file containing the text blocks.
Returns:
dict: A dictionary where keys are block IDs and values are the text content.
Returns an empty dictionary if the file is not found or invalid.
"""
try:
with open(filepath, 'r') as f:
data = json.load(f) # Load JSON data from the file
text_blocks = {}
for block_id, text in data.items(): # Iterate through the loaded data
text_blocks[block_id] = text # Store text in the dictionary
return text_blocks
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return {} # Return empty dictionary if file not found
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in {filepath}")
return {} # Return empty dictionary if JSON is invalid
if __name__ == '__main__':
# Example usage:
text_data = load_text_blocks('text_blocks.json') # Replace with your file path
if text_data:
print("Text blocks loaded successfully:")
for block_id, text in text_data.items():
print(f"Block ID: {block_id}")
print(f"Text: {text[:50]}...") # Print first 50 chars of text
else:
print("Failed to load text blocks.")
Add your comment