Certainly! To modify the provided code to focus exclusively on tracking unmatched entries (i.e., entries that do not contain the specified phrases), we can streamline the functionality to concentrate on identifying and handling these unmatched entries.
Here's how you can adjust the existing code:
-
Rename Functions for Clarity: To avoid confusion between tracking matched and unmatched entries, we'll focus on a single function that specifically tracks unmatched entries.
-
Enhance Logging and Output: Ensure that the function provides clear and concise information about which entries are unmatched and why.
-
Remove or Adjust the Second Function: Since the primary focus is on tracking unmatched entries, you might consider removing or adjusting the find_phrase_in_explanations function if it's no longer necessary for your workflow.
Below is the modified code with these considerations:
import json
import os
import re
def track_unmatched_entries(
input_path,
phrases=["unrelated"],
verbose=True,
case_sensitive=False,
save_unmatched_ids=False,
output_path="unmatched_ids.txt"
):
"""
Tracks and records entries in the JSON file where the 'explanation' field
does NOT contain all specified phrases. Prints the 'id' of these unmatched entries.
Args:
input_path (str): Path to the input JSON file (e.g., 'synonymtemp1.json').
phrases (list of str): The phrases that should be present in the 'explanation' field.
verbose (bool): If True, prints detailed warnings and information.
case_sensitive (bool): If True, the search is case-sensitive.
save_unmatched_ids (bool): If True, saves the unmatched ids to a text file.
output_path (str): Path to save the unmatched ids if `save_unmatched_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 of unmatched entries
unmatched_ids = []
# Prepare regex 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.")
unmatched_ids.append(entry_id)
continue
# Identify missing 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)}.")
unmatched_ids.append(entry_id)
# Summary of unmatched entries
if unmatched_ids:
print("\nUnmatched Entries (missing one or more specified phrases):")
for eid in unmatched_ids:
print(eid)
else:
print(f"All entries contain all specified phrases in their explanations.")
# Optionally, save the unmatched ids to a file
if save_unmatched_ids:
try:
with open(output_path, 'w', encoding='utf-8') as out_file:
for eid in unmatched_ids:
out_file.write(f"{eid}\n")
print(f"\nUnmatched 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\synonymnew1.json'
# Track unmatched entries
track_unmatched_entries(
input_path=input_file,
phrases=["unrelated"], # List of phrases to check
verbose=True,
case_sensitive=False, # Set to True if the search should be case-sensitive
save_unmatched_ids=True, # Set to True to save the unmatched ids to a file
output_path="unmatched_ids.txt" # File to save unmatched ids
)
Key Modifications Explained:
-
Function Renaming:
- Old Function:
check_phrases_in_explanation
- New Function:
track_unmatched_entries
Renaming clarifies that the function is specifically tracking unmatched entries.
-
Simplified Functionality:
- Removed the second function
find_phrase_in_explanations to focus solely on tracking unmatched entries. If you still need the capability to track matched entries, you can retain and adjust the second function accordingly.
-
Enhanced Verbose Messages:
- Provides clear warnings when an
explanation is empty or when specific phrases are missing.
- Summarizes all unmatched entries at the end.
-
Consistent Terminology:
- Changed variable names from
missing_ids to unmatched_ids for consistency and clarity.
-
Modular Output Options:
- Provides the option to save unmatched IDs to a file, enhancing usability for larger datasets.
Optional: Retain the Function to Track Matched Entries
If you still require the functionality to track matched entries, you can keep both functions but ensure that their purposes are clear. Here's a brief overview:
track_unmatched_entries: Tracks entries that do not contain all specified phrases.
find_phrase_in_explanations: (Original function) Tracks entries that do contain a specific phrase.
You might consider organizing these functions within a class or separate modules if your project scales up.
Sample JSON Structure
Ensure that your JSON file (synonymnew1.json in your case) has a structure similar to the following:
[
{
"id": "1",
"explanation": "This is an unrelated explanation."
},
{
"id": "2",
"explanation": "This explanation is related."
},
{
"id": "3",
"explanation": ""
}
]
Running the Script
-
Save the Script: Save the modified script to a .py file, for example, track_unmatched.py.
-
Execute the Script: Run the script using Python:
python track_unmatched.py
-
Output:
- The script will print warnings and summaries of unmatched entries based on the specified phrases.
- If
save_unmatched_ids is set to True, it will save the IDs of unmatched entries to unmatched_ids.txt.
Customization
-
Phrases to Check: Modify the phrases list to include all phrases you want each entry's explanation to contain.
phrases=["unrelated", "another_phrase"]
-
Case Sensitivity: Adjust the case_sensitive parameter based on your requirements.
-
Output Paths: Change output_path to direct the unmatched IDs to a desired location.
Conclusion
This modified script focuses on tracking entries that do not meet the specified criteria (i.e., missing certain phrases in their explanation fields). It provides clear output and optional saving of unmatched IDs for further analysis or processing.
If you need further customization or additional features, feel free to ask!