Give me a python code that would accumulate correct_answer words from a local json file and prints the words (only unique ones). A sample entry in the json file is provide below:
{
"type": "seneq",
"id": 415,
"quiztype": "textcompletion",
"explanation": "The company's decision to reduce its workforce during the economic downturn suggests 'diminish' and 'curtail'. 'Diminish' means to make or become less. 'Curtail' means to reduce or limit something. 'Augment' (increase), 'bolster' (support or strengthen), 'enhance' (improve), and 'expand' (increase in size) do not fit with reducing the workforce.",
"correct_answer": [
"diminish",
"curtail"
],
"question": "The company's decision to ________ its workforce during the economic downturn was met with widespread criticism from both employees and labor unions.",
"options": {
"F": "expand",
"A": "augment",
"D": "curtail",
"C": "bolster",
"B": "diminish",
"E": "enhance"
}
}
Assistant
Certainly! Below is a Python script that reads a local JSON file, accumulates all the words from the correct_answer fields across all entries, and prints out only the unique words.
Assumptions:
JSON File Structure: The JSON file is assumed to contain a list (array) of objects, where each object is similar to the sample entry you provided.
File Encoding: The JSON file is encoded in UTF-8.
File Name: Replace 'data.json' with the path to your actual JSON file.
Python Script:
python
import json
def get_unique_correct_answers(file_path):
"""
Reads a JSON file, extracts all words from the 'correct_answer' fields,
and returns a set of unique words.
:param file_path: Path to the JSON file.
:return: A set of unique correct answer words.
"""
unique_answers = set()
try:
with open(file_path, 'r', encoding='utf-8') as file:
# Load the JSON data
data = json.load(file)
# Check if the data is a list
if isinstance(data, list):
for entry in data:
# Ensure 'correct_answer' exists and is a list
correct_answers = entry.get('correct_answer', [])
if isinstance(correct_answers, list):
unique_answers.update(correct_answers)
else:
print(f"Warning: 'correct_answer' is not a list in entry ID {entry.get('id')}")
elif isinstance(data, dict):
# If the JSON root is a single object
correct_answers = data.get('correct_answer', [])
if isinstance(correct_answers, list):
unique_answers.update(correct_answers)
else:
print("Warning: 'correct_answer' is not a list in the JSON root object.")
else:
print("Unsupported JSON structure. The JSON root should be a list or an object.")
except FileNotFoundError:
print(f"Error: The file {file_path} was not found.")
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return unique_answers
def main():
# Replace 'data.json' with the path to your JSON file
file_path = 'data.json'
unique_words = get_unique_correct_answers(file_path)
if unique_words:
print("Unique correct answer words:")
for word in sorted(unique_words):
print(word)
else:
print("No correct answer words found.")
if __name__ == "__main__":
main()
Explanation:
Function get_unique_correct_answers:
Purpose: Reads the JSON file and extracts unique words from all correct_answer fields.
Process:
Opens the JSON file and loads its content.
Checks if the JSON root is a list or a single object.
Iterates through each entry and updates the unique_answers set with words from correct_answer.
Handles potential issues like missing files or JSON decoding errors gracefully.
Function main:
Defines the file path to the JSON file.
Calls get_unique_correct_answers to retrieve the unique words.
Prints the unique words in sorted order for better readability.
Execution Guard:
The if __name__ == "__main__": block ensures that main() runs only when the script is executed directly, not when imported as a module.
Sample JSON File (data.json):
Ensure your JSON file is structured as a list of entries like the sample provided. Here's an example of how data.json might look:
json
[
{
"type": "seneq",
"id": 415,
"quiztype": "textcompletion",
"explanation": "The company's decision to reduce its workforce during the economic downturn suggests 'diminish' and 'curtail'. 'Diminish' means to make or become less. 'Curtail' means to reduce or limit something. 'Augment' (increase), 'bolster' (support or strengthen), 'enhance' (improve), and 'expand' (increase in size) do not fit with reducing the workforce.",
"correct_answer": [
"diminish",
"curtail"
],
"question": "The company's decision to ________ its workforce during the economic downturn was met with widespread criticism from both employees and labor unions.",
"options": {
"F": "expand",
"A": "augment",
"D": "curtail",
"C": "bolster",
"B": "diminish",
"E": "enhance"
}
},
{
"type": "seneq",
"id": 416,
"quiztype": "textcompletion",
"explanation": "Another explanation here.",
"correct_answer": [
"augment",
"enhance"
],
"question": "Example question here.",
"options": {
"F": "expand",
"A": "augment",
"D": "curtail",
"C": "bolster",
"B": "diminish",
"E": "enhance"
}
}
// Add more entries as needed
]
Running the Script:
Save the Script: Save the Python script to a file, e.g., extract_unique_answers.py.
Prepare the JSON File: Ensure your JSON file (data.json) is in the same directory as the script or provide the correct path.