openai_humaneval-th / parse_check.py
kobkrit's picture
Fix with new file
df50c21
import json
import re
import os
def fix_json_string(json_str):
# Replace single backslashes with double backslashes
# but only when they're not already properly escaped
return re.sub(r'(?<!\\)\\(?!["\\])', r'\\\\', json_str)
def check_and_fix_jsonl_file(input_file_path):
# Create output filename by adding '_fixed' before the extension
base, ext = os.path.splitext(input_file_path)
output_file_path = f"{base}_fixed{ext}"
fixed_lines = []
has_errors = False
with open(input_file_path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
try:
# Try to fix the JSON string before parsing
fixed_line = fix_json_string(line)
# Verify the fix worked by parsing
json.loads(fixed_line)
fixed_lines.append(fixed_line)
except json.JSONDecodeError as e:
has_errors = True
print(f"Error on line {line_num}: {str(e)}")
print(f"Problematic line content: {line.strip()}")
if has_errors:
print("\nSome lines had errors and may not be properly fixed.")
# Write the fixed lines to the new file
with open(output_file_path, 'w', encoding='utf-8') as f:
f.writelines(fixed_lines)
print(f"\nFixed JSONL file saved to: {output_file_path}")
if __name__ == "__main__":
file_path = "data/test.jsonl"
print(f"Checking and fixing file: {file_path}")
check_and_fix_jsonl_file(file_path)
print("Process complete")