Sure! To modify the provided Python code to check for the phrase "is also an antonym" instead of "sounds similar", you'll need to update the phrase parameter in both the function definition (if you want to change the default) and the example usage.
Below is the updated code with the necessary changes:
import json
import os
import re
def check_phrase_in_explanation(input_path, phrase="is also an antonym", verbose=True, case_sensitive=False, save_missing_ids=False, output_path="missing_ids.txt"):
"""
Checks each entry in the JSON file to see if the 'explanation' field contains a specific phrase.
Prints the 'id' of entries where the phrase is not found.
Args:
input_path (str): Path to the input JSON file (e.g., 'synonymtemp1.json').
phrase (str): The phrase to search for in the 'explanation' field.
verbose (bool): If True, prints detailed warnings and information.
case_sensitive (bool): If True, the search is case-sensitive.
save_missing_ids (bool): If True, saves the missing ids to a text file.
output_path (str): Path to save the missing ids if `save_missing_ids` is True.
"""
# Check if the input file exists
if not os.path.exists(input_path):
print(f"Error: The file '{input_path}' does not exist.")
return
# Load the JSON data
try:
with open(input_path, 'r', encoding='utf-8') as file:
data = json.load(file)
except json.JSONDecodeError as e:
print(f"Error decoding JSON from '{input_path}': {e}")
return
# Ensure the JSON data is a list
if not isinstance(data, list):
print(f"Error: Expected the JSON data to be a list of entries in '{input_path}'.")
return
# List to store ids missing the phrase
missing_ids = []
# Compile the search pattern
flags = 0
if not case_sensitive:
flags = re.IGNORECASE
# Escape the phrase to handle any special regex characters
pattern = re.compile(re.escape(phrase), flags)
# Iterate through each entry
for entry in data:
entry_id = entry.get('id', 'Unknown ID')
explanation = entry.get('explanation', '')
if not explanation:
if verbose:
print(f"Warning: Entry with id '{entry_id}' has an empty 'explanation' field.")
missing_ids.append(entry_id)
continue
# Search for the phrase in the explanation
if not pattern.search(explanation):
if verbose:
print(f"Entry with id '{entry_id}' is missing the phrase '{phrase}'.")
missing_ids.append(entry_id)
# Print the results
if missing_ids:
print("\nEntries missing the phrase '{}':".format(phrase))
for eid in missing_ids:
print(eid)
else:
print(f"All entries contain the phrase '{phrase}' in their explanations.")
# Optionally, save the missing ids to a file
if save_missing_ids:
try:
with open(output_path, 'w', encoding='utf-8') as out_file:
for eid in missing_ids:
out_file.write(f"{eid}\n")
print(f"\nMissing ids have been saved to '{output_path}'.")
except IOError as e:
print(f"Error writing to '{output_path}': {e}")
# Example usage
if __name__ == "__main__":
# Define the path to your JSON file
input_file = r'D:\DBImportExport\AllJsonFiles\synonymtemp1.json'
# Call the function with desired parameters
check_phrase_in_explanation(
input_path=input_file,
phrase="is also an antonym", # Updated phrase to check
verbose=True,
case_sensitive=False, # Set to True if the search should be case-sensitive
save_missing_ids=True, # Set to True to save the missing ids to a file
output_path="missing_ids.txt" # File to save missing ids
)
Changes Made:
-
Default Phrase Update (Optional):
- Before:
def check_phrase_in_explanation(input_path, phrase="sounds similar", ...)
- After:
def check_phrase_in_explanation(input_path, phrase="is also an antonym", ...)
This change sets the default phrase to "is also an antonym". If you want the default to remain "sounds similar" and only change it during usage, you can skip this modification.
-
Example Usage Update:
The primary change is in the phrase parameter within the check_phrase_in_explanation function call. It now checks for "is also an antonym" instead of "sounds similar".
check_phrase_in_explanation(
input_path=input_file,
phrase="is also an antonym", # Updated phrase to check
...
)
Additional Enhancements (Optional)
If you want to enhance the function to check for multiple phrases (e.g., both "sounds similar" and "is also an antonym"), you can modify the function to accept a list of phrases and iterate through them. Here's how you can do it:
def check_phrases_in_explanation(input_path, phrases=["is also an antonym"], verbose=True, case_sensitive=False, save_missing_ids=False, output_path="missing_ids.txt"):
"""
Checks each entry in the JSON file to see if the 'explanation' field contains all specified phrases.
Prints the 'id' of entries where any of the phrases are not found.
Args:
input_path (str): Path to the input JSON file (e.g., 'synonymtemp1.json').
phrases (list of str): The phrases to search for in the 'explanation' field.
verbose (bool): If True, prints detailed warnings and information.
case_sensitive (bool): If True, the search is case-sensitive.
save_missing_ids (bool): If True, saves the missing ids to a text file.
output_path (str): Path to save the missing ids if `save_missing_ids` is True.
"""
# Check if the input file exists
if not os.path.exists(input_path):
print(f"Error: The file '{input_path}' does not exist.")
return
# Load the JSON data
try:
with open(input_path, 'r', encoding='utf-8') as file:
data = json.load(file)
except json.JSONDecodeError as e:
print(f"Error decoding JSON from '{input_path}': {e}")
return
# Ensure the JSON data is a list
if not isinstance(data, list):
print(f"Error: Expected the JSON data to be a list of entries in '{input_path}'.")
return
# List to store ids missing any of the phrases
missing_ids = []
# Compile the search patterns
flags = 0
if not case_sensitive:
flags = re.IGNORECASE
patterns = [re.compile(re.escape(phrase), flags) for phrase in phrases]
# Iterate through each entry
for entry in data:
entry_id = entry.get('id', 'Unknown ID')
explanation = entry.get('explanation', '')
if not explanation:
if verbose:
print(f"Warning: Entry with id '{entry_id}' has an empty 'explanation' field.")
missing_ids.append(entry_id)
continue
# Check all phrases
missing_phrases = [phrase for phrase, pattern in zip(phrases, patterns) if not pattern.search(explanation)]
if missing_phrases:
if verbose:
print(f"Entry with id '{entry_id}' is missing the phrase(s): {', '.join(missing_phrases)}.")
missing_ids.append(entry_id)
# Print the results
if missing_ids:
print("\nEntries missing one or more specified phrases.")
for eid in missing_ids:
print(eid)
else:
print(f"All entries contain all specified phrases in their explanations.")
# Optionally, save the missing ids to a file
if save_missing_ids:
try:
with open(output_path, 'w', encoding='utf-8') as out_file:
for eid in missing_ids:
out_file.write(f"{eid}\n")
print(f"\nMissing ids have been saved to '{output_path}'.")
except IOError as e:
print(f"Error writing to '{output_path}': {e}")
# Example usage for multiple phrases
if __name__ == "__main__":
# Define the path to your JSON file
input_file = r'D:\DBImportExport\AllJsonFiles\synonymtemp1.json'
# Call the function with desired parameters
check_phrases_in_explanation(
input_path=input_file,
phrases=["is also an antonym", "sounds similar"], # List of phrases to check
verbose=True,
case_sensitive=False, # Set to True if the search should be case-sensitive
save_missing_ids=True, # Set to True to save the missing ids to a file
output_path="missing_ids.txt" # File to save missing ids
)
Explanation of Enhancements:
-
Multiple Phrase Checking: The enhanced function check_phrases_in_explanation accepts a list of phrases and checks if each one is present in the explanation field. It reports entries missing any of the specified phrases.
-
Flexible Usage: You can specify as many phrases as needed by adding them to the phrases list in the function call.
Final Notes
-
Case Sensitivity: The case_sensitive parameter controls whether the search is case-sensitive. Set it to True if you want "Is also an Antonym" to be treated differently from "is also an antonym".
-
Saving Missing IDs: When save_missing_ids is set to True, the IDs of entries missing the specified phrase(s) will be saved to the file specified by output_path. Ensure that the script has write permissions to the directory where you're trying to save the file.
-
Error Handling: The script includes error handling for scenarios like missing input files, invalid JSON formats, and issues while writing to the output file.
Feel free to adjust the paths and parameters as needed for your specific use case!