Datasets:

Modalities:
Text
ArXiv:
File size: 1,339 Bytes
f9dff7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import re
import pathlib
import shutil
import argparse

def escape_backslashes_in_questions(text: str) -> str:
    # 匹配 "question": "..."
    json_string = r'"(?:\\.|[^"\\])*"'
    pattern = re.compile(rf'("question"\s*:\s*)({json_string})')

    def replacer(m):
        prefix, raw = m.groups()
        # 去掉外层引号
        inner = raw[1:-1]
        # 把单反斜杠替换成双反斜杠
        inner_fixed = inner.replace("\\", "\\\\")
        return f'{prefix}"{inner_fixed}"'

    return pattern.sub(replacer, text)

def process_file(p: pathlib.Path):
    original = p.read_text(encoding="utf-8")
    fixed = escape_backslashes_in_questions(original)
    if fixed != original:
        shutil.copyfile(p, p.with_suffix(p.suffix + ".bak"))
        p.write_text(fixed, encoding="utf-8")
        print(f"[UPDATED] {p}")
    else:
        print(f"[SKIP   ] {p}")

def main():
    ap = argparse.ArgumentParser(description="Fix backslashes in 'question' fields of JSON files")
    ap.add_argument("folder", type=str, help="Directory containing .json files")
    args = ap.parse_args()

    root = pathlib.Path(args.folder)
    if not root.is_dir():
        print(f"[ERROR] {args.folder} is not a valid directory")
        return

    for p in root.glob("*.json"):
        process_file(p)

if __name__ == "__main__":
    main()