scripts/encoding_convert.py
5.9 KB| 1 | #!/usr/bin/env python3 |
| 2 | """文本文件编码检测与批量转换。 |
| 3 | |
| 4 | 纯标准库,不联网。默认只预览,加 --apply 才写入,并生成 .bak 备份。 |
| 5 | """ |
| 6 | |
| 7 | import argparse |
| 8 | import os |
| 9 | import sys |
| 10 | |
| 11 | BOMS = { |
| 12 | b"\xef\xbb\xbf": "utf-8-sig", |
| 13 | b"\xff\xfe": "utf-16-le", |
| 14 | b"\xfe\xff": "utf-16-be", |
| 15 | } |
| 16 | |
| 17 | TARGET_ALIASES = { |
| 18 | "utf-8": "utf-8", |
| 19 | "utf8": "utf-8", |
| 20 | "utf-8-sig": "utf-8-sig", |
| 21 | "utf8-sig": "utf-8-sig", |
| 22 | "gb18030": "gb18030", |
| 23 | "gbk": "gb18030", |
| 24 | "gb2312": "gb18030", |
| 25 | "utf-16": "utf-16", |
| 26 | } |
| 27 | |
| 28 | |
| 29 | def detect_encoding(data: bytes) -> str: |
| 30 | """返回检测到的编码名,无法判断时返回 unknown。""" |
| 31 | for bom, name in BOMS.items(): |
| 32 | if data.startswith(bom): |
| 33 | return name |
| 34 | |
| 35 | try: |
| 36 | data.decode("utf-8", errors="strict") |
| 37 | return "utf-8" |
| 38 | except UnicodeDecodeError: |
| 39 | pass |
| 40 | |
| 41 | try: |
| 42 | data.decode("gb18030", errors="strict") |
| 43 | return "gb18030" |
| 44 | except UnicodeDecodeError: |
| 45 | pass |
| 46 | |
| 47 | return "unknown" |
| 48 | |
| 49 | |
| 50 | def decode_bytes(data: bytes, encoding: str) -> str: |
| 51 | """按检测到的编码解码为文本。""" |
| 52 | if encoding == "utf-8-sig": |
| 53 | return data.decode("utf-8-sig") |
| 54 | if encoding == "utf-16-le": |
| 55 | return data[2:].decode("utf-16-le") |
| 56 | if encoding == "utf-16-be": |
| 57 | return data[2:].decode("utf-16-be") |
| 58 | return data.decode(encoding) |
| 59 | |
| 60 | |
| 61 | def encode_text(text: str, target: str, with_bom: bool) -> bytes: |
| 62 | """把文本按目标编码编码为字节。""" |
| 63 | if target == "utf-8": |
| 64 | raw = text.encode("utf-8") |
| 65 | return b"\xef\xbb\xbf" + raw if with_bom else raw |
| 66 | if target == "utf-8-sig": |
| 67 | return text.encode("utf-8-sig") |
| 68 | if target == "gb18030": |
| 69 | return text.encode("gb18030") |
| 70 | if target == "utf-16": |
| 71 | return text.encode("utf-16") # 自带 BOM |
| 72 | raise ValueError(f"不支持的目标编码:{target}") |
| 73 | |
| 74 | |
| 75 | def collect_files(path: str, exts): |
| 76 | """展开待处理文件列表。""" |
| 77 | if os.path.isfile(path): |
| 78 | return [path] |
| 79 | |
| 80 | found = [] |
| 81 | for root, _dirs, files in os.walk(path): |
| 82 | for name in sorted(files): |
| 83 | if os.path.splitext(name)[1].lower() in exts: |
| 84 | found.append(os.path.join(root, name)) |
| 85 | return found |
| 86 | |
| 87 | |
| 88 | def normalize_target(target: str) -> str: |
| 89 | key = target.lower().strip() |
| 90 | if key not in TARGET_ALIASES: |
| 91 | raise ValueError(f"不支持的目标编码:{target}") |
| 92 | return TARGET_ALIASES[key] |
| 93 | |
| 94 | |
| 95 | def main(): |
| 96 | parser = argparse.ArgumentParser(description="文本编码检测与批量转换(默认只预览)") |
| 97 | parser.add_argument("path", help="文件或目录") |
| 98 | parser.add_argument("--to", required=True, help="目标编码:utf-8 / utf-8-sig / gb18030 / utf-16") |
| 99 | parser.add_argument("--apply", action="store_true", help="真正写入文件") |
| 100 | parser.add_argument( |
| 101 | "--ext", |
| 102 | default=".txt,.csv,.md,.log,.json,.srt", |
| 103 | help="参与处理的扩展名,逗号分隔", |
| 104 | ) |
| 105 | parser.add_argument("--bom", action="store_true", help="输出 UTF-8 时附带 BOM") |
| 106 | parser.add_argument("--no-backup", action="store_true", help="不生成 .bak 备份") |
| 107 | args = parser.parse_args() |
| 108 | |
| 109 | try: |
| 110 | target = normalize_target(args.to) |
| 111 | except ValueError as exc: |
| 112 | print(f"错误:{exc}", file=sys.stderr) |
| 113 | return 2 |
| 114 | |
| 115 | if not os.path.exists(args.path): |
| 116 | print(f"错误:路径不存在 {args.path}", file=sys.stderr) |
| 117 | return 2 |
| 118 | |
| 119 | exts = {e.strip().lower() for e in args.ext.split(",") if e.strip()} |
| 120 | files = collect_files(args.path, exts) |
| 121 | |
| 122 | if not files: |
| 123 | print(f"提示:在 {args.path} 下未找到可处理的文本文件", file=sys.stderr) |
| 124 | return 1 |
| 125 | |
| 126 | converted = skipped = failed = 0 |
| 127 | mode = "转换" if args.apply else "预览" |
| 128 | |
| 129 | for file_path in files: |
| 130 | try: |
| 131 | with open(file_path, "rb") as fh: |
| 132 | data = fh.read() |
| 133 | except OSError as exc: |
| 134 | print(f"[失败] {file_path}:读取错误 {exc}") |
| 135 | failed += 1 |
| 136 | continue |
| 137 | |
| 138 | source = detect_encoding(data) |
| 139 | |
| 140 | if source == "unknown": |
| 141 | print(f"[跳过] {file_path}:无法判定编码,未改动") |
| 142 | failed += 1 |
| 143 | continue |
| 144 | |
| 145 | if source == target: |
| 146 | print(f"[跳过] {file_path}:已是目标编码 {source}") |
| 147 | skipped += 1 |
| 148 | continue |
| 149 | |
| 150 | source_is_utf8_family = source in ("utf-8", "utf-8-sig") |
| 151 | target_is_utf8_family = target in ("utf-8", "utf-8-sig") |
| 152 | |
| 153 | if source_is_utf8_family and target_is_utf8_family: |
| 154 | has_bom = data.startswith(b"\xef\xbb\xbf") |
| 155 | want_bom = args.bom or target == "utf-8-sig" |
| 156 | if has_bom == want_bom: |
| 157 | print(f"[跳过] {file_path}:已是目标编码 {source}") |
| 158 | skipped += 1 |
| 159 | continue |
| 160 | |
| 161 | try: |
| 162 | text = decode_bytes(data, source) |
| 163 | new_bytes = encode_text(text, target, args.bom) |
| 164 | except (UnicodeDecodeError, UnicodeEncodeError) as exc: |
| 165 | print(f"[失败] {file_path}:转换失败 {exc}") |
| 166 | failed += 1 |
| 167 | continue |
| 168 | |
| 169 | if args.apply: |
| 170 | if not args.no_backup: |
| 171 | backup_path = file_path + ".bak" |
| 172 | if not os.path.exists(backup_path): |
| 173 | with open(backup_path, "wb") as fh: |
| 174 | fh.write(data) |
| 175 | with open(file_path, "wb") as fh: |
| 176 | fh.write(new_bytes) |
| 177 | print(f"[转换] {file_path}:{source} -> {target}") |
| 178 | else: |
| 179 | print(f"[预览] {file_path}:{source} -> {target}") |
| 180 | |
| 181 | converted += 1 |
| 182 | |
| 183 | print( |
| 184 | f"\n{mode}完成:共 {len(files)} 个文件," |
| 185 | f"待转换/已转换 {converted},跳过 {skipped},失败或无法判定 {failed}" |
| 186 | ) |
| 187 | if not args.apply and converted: |
| 188 | print("当前为预览模式,确认无误后加 --apply 才能真正写入。") |
| 189 | return 0 if failed == 0 else 1 |
| 190 | |
| 191 | |
| 192 | if __name__ == "__main__": |
| 193 | sys.exit(main()) |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

