1. import json
  2. def load_text_blocks(filepath):
  3. """
  4. Loads text blocks from a JSON file.
  5. Args:
  6. filepath (str): The path to the JSON file containing the text blocks.
  7. Returns:
  8. dict: A dictionary where keys are block IDs and values are the text content.
  9. Returns an empty dictionary if the file is not found or invalid.
  10. """
  11. try:
  12. with open(filepath, 'r') as f:
  13. data = json.load(f) # Load JSON data from the file
  14. text_blocks = {}
  15. for block_id, text in data.items(): # Iterate through the loaded data
  16. text_blocks[block_id] = text # Store text in the dictionary
  17. return text_blocks
  18. except FileNotFoundError:
  19. print(f"Error: File not found at {filepath}")
  20. return {} # Return empty dictionary if file not found
  21. except json.JSONDecodeError:
  22. print(f"Error: Invalid JSON format in {filepath}")
  23. return {} # Return empty dictionary if JSON is invalid
  24. if __name__ == '__main__':
  25. # Example usage:
  26. text_data = load_text_blocks('text_blocks.json') # Replace with your file path
  27. if text_data:
  28. print("Text blocks loaded successfully:")
  29. for block_id, text in text_data.items():
  30. print(f"Block ID: {block_id}")
  31. print(f"Text: {text[:50]}...") # Print first 50 chars of text
  32. else:
  33. print("Failed to load text blocks.")

Add your comment