give me a python code that reads synonymnew.json (local file) and lists the words in the…
- User
give me a python code that reads synonymnew.json (local file) and lists the words in the 'question' entry. In case of repetition it prints the count of that particular word adjacent to it.
Sample entry in synonymnew.json:
{ "id": 14, "quiztype": "quickquiz", "type": "synonyms", "question": "insidious", "options": [ "treacherous", "obvious", "benign", "harmless" ], "answer": "treacherous", "explanation": "The correct answer is 'treacherous.' \n\n'Insidious' means proceeding in a gradual, subtle way, but with harmful effects. It is synonymous with 'treacherous,' as both words describe something dangerous or harmful that is not easily noticed. \n\n'Obvious' is an antonym, as it describes something easily perceived or understood. 'Benign' and 'harmless' are also antonyms, describing things that do not cause harm. \n\nAn insidious disease, for example, might progress slowly without obvious symptoms, making it particularly dangerous." }
- Assistant
Certainly! Below is a Python script that reads a local
synonymnew.jsonfile, extracts all the words from thequestionentries, and prints each word. If a word appears multiple times, the script will display the count adjacent to it.Steps the Script Performs:
-
Import Necessary Modules:
jsonfor handling JSON data.collections.Counterfor counting occurrences of each word.
-
Load JSON Data:
- Open and read the
synonymnew.jsonfile. - Parse the JSON data assuming it's a list of dictionary entries.
- Open and read the
-
Extract
questionWords:- Iterate through each entry and collect the words from the
questionfield. - If the
questioncontains multiple words, they are split accordingly.
- Iterate through each entry and collect the words from the
-
Count Word Occurrences:
- Use
Counterto count how many times each word appears.
- Use
-
Display the Results:
- Iterate through the counted words.
- Print each word. If a word appears more than once, print the count next to it.
Sample
synonymnew.jsonStructure:[ { "id": 14, "quiztype": "quickquiz", "type": "synonyms", "question": "insidious", "options": [ "treacherous", "obvious", "benign", "harmless" ], "answer": "treacherous", "explanation": "The correct answer is 'treacherous.' ..." }, { "id": 15, "quiztype": "quickquiz", "type": "synonyms", "question": "obvious", "options": [ "clear", "hidden", "complex", "simple" ], "answer": "clear", "explanation": "The correct answer is 'clear.' ..." }, { "id": 16, "quiztype": "quickquiz", "type": "synonyms", "question": "insidious", "options": [ "covert", "transparent", "glossy", "slippery" ], "answer": "covert", "explanation": "The correct answer is 'covert.' ..." } ]Python Script (
count_questions.py):import json from collections import Counter import os def count_question_words(file_path): # Check if the file exists if not os.path.isfile(file_path): print(f"File '{file_path}' does not exist.") return try: with open(file_path, 'r', encoding='utf-8') as file: data = json.load(file) # Ensure the JSON data is a list if not isinstance(data, list): print("JSON data is not a list of entries.") return # Extract all words from the 'question' entries words = [] for entry in data: question = entry.get('question', '') # Split the question into words if it's a sentence words_in_question = question.split() words.extend(words_in_question) # Count occurrences of each word word_counts = Counter(words) # Print words with counts if they appear more than once for word, count in word_counts.items(): if count > 1: print(f"{word} {count}") else: print(word) except json.JSONDecodeError: print("Error decoding JSON. Please check the JSON file format.") except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": # Specify the path to your JSON file json_file_path = 'synonymnew.json' count_question_words(json_file_path)How to Use the Script:
-
Ensure File Location:
- Place the
count_questions.pyscript in the same directory as yoursynonymnew.jsonfile. - Alternatively, specify the correct path to
synonymnew.jsonin thejson_file_pathvariable.
- Place the
-
Run the Script:
-
Open your terminal or command prompt.
-
Navigate to the directory containing the script.
-
Execute the script using Python:
python count_questions.py
-
-
Expected Output:
-
Based on the sample
synonymnew.jsonprovided above, the output will be:insidious 2 obvious -
Here, "insidious" appears twice, so it is displayed with a count of 2. "obvious" appears once and is displayed without a count.
-
Notes:
-
Handling Multiple Words:
- If a
questionentry contains multiple words (e.g., "quick brown fox"), each word is counted separately.
- If a
-
Error Handling:
- The script includes basic error handling for scenarios such as missing files or invalid JSON formats.
-
Customization:
- You can modify the script to change the output format or handle different JSON structures as needed.
Feel free to customize and expand upon this script based on the specific structure and requirements of your
synonymnew.jsonfile! -