| | |
| | |
| |
|
| | import argparse |
| | import pathlib |
| | import re |
| | import shutil |
| |
|
| | def remove_explanation_fields(text: str) -> str: |
| | """ |
| | 删除 JSON 文本中键为 "explanation" 的键值对(值为字符串), |
| | 不使用 json 解析,使用正则在词法层面安全处理转义字符。 |
| | 同时正确处理前后逗号,保持 JSON 仍然有效。 |
| | """ |
| |
|
| | |
| | |
| | json_string = r'"(?:\\.|[^"\\])*"' |
| |
|
| | |
| | |
| | pattern_after = re.compile( |
| | rf'\s*"explanation"\s*:\s*{json_string}\s*,' |
| | ) |
| |
|
| | |
| | |
| | pattern_before = re.compile( |
| | rf',\s*"explanation"\s*:\s*{json_string}' |
| | ) |
| |
|
| | |
| | new_text = pattern_after.sub('', text) |
| | new_text = pattern_before.sub('', new_text) |
| |
|
| | |
| | |
| | |
| | |
| |
|
| | return new_text |
| |
|
| | def process_file(p: pathlib.Path, dry_run: bool = False) -> bool: |
| | original = p.read_text(encoding='utf-8') |
| | repaired = remove_explanation_fields(original) |
| | if repaired != original: |
| | if not dry_run: |
| | |
| | backup = p.with_suffix(p.suffix + '.bak') |
| | shutil.copyfile(p, backup) |
| | |
| | p.write_text(repaired, encoding='utf-8') |
| | return True |
| | return False |
| |
|
| | def main(): |
| | ap = argparse.ArgumentParser( |
| | description="在不使用 json 解析的前提下,删除所有 JSON 文件中的 \"explanation\": \"...\" 字段(安全处理转义字符与逗号)。" |
| | ) |
| | ap.add_argument("folder", type=str, help="包含 .json 文件的文件夹路径") |
| | ap.add_argument("--dry-run", action="store_true", help="仅显示将要修改的文件,不写回") |
| | args = ap.parse_args() |
| |
|
| | root = pathlib.Path(args.folder) |
| | if not root.is_dir(): |
| | raise SystemExit(f"路径不存在或不是文件夹:{root}") |
| |
|
| | changed = 0 |
| | total = 0 |
| | for p in sorted(root.glob("*.json")): |
| | total += 1 |
| | if process_file(p, dry_run=args.dry_run): |
| | changed += 1 |
| | print(f"[UPDATED] {p}") |
| | else: |
| | print(f"[SKIP ] {p}(无 explanation 字段或无需修改)") |
| |
|
| | print(f"\n完成:扫描 {total} 个 .json 文件,修改 {changed} 个。") |
| | if not args.dry_run: |
| | print("已为修改过的文件生成 .bak 备份。") |
| |
|
| | if __name__ == "__main__": |
| | main() |
| |
|