zhconv_txt.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #!/usr/bin/env python3
  2. import sys
  3. import os
  4. import argparse
  5. from pathlib import Path
  6. try:
  7. from zhconv import convert
  8. except ImportError:
  9. sys.exit("错误:请先安装依赖库,执行命令:pip install zhconv")
  10. def safe_filename(base_path, prefix='converted_'):
  11. """生成唯一的新文件名"""
  12. path = Path(base_path)
  13. new_stem = f"{prefix}{path.stem}"
  14. new_path = path.with_stem(new_stem)
  15. counter = 0
  16. while new_path.exists():
  17. counter += 1
  18. new_stem = f"{prefix}{counter}_{path.stem}"
  19. new_path = path.with_stem(new_stem)
  20. return new_path
  21. def detect_and_read(filepath):
  22. """智能检测编码并读取内容"""
  23. encodings = ['utf-8', 'gb18030', 'big5', 'latin-1']
  24. with open(filepath, 'rb') as f:
  25. raw_data = f.read()
  26. for enc in encodings:
  27. try:
  28. return raw_data.decode(enc)
  29. except UnicodeDecodeError:
  30. continue
  31. raise UnicodeDecodeError("无法识别的文件编码")
  32. def convert_file(input_path, prefix='', to_traditional=False, region='tw'):
  33. """支持多地区转换的核心函数"""
  34. try:
  35. content = detect_and_read(input_path)
  36. # 确定转换方向
  37. if to_traditional:
  38. target = 'zh-hk' if region == 'hk' else 'zh-tw'
  39. direction = f"s2t_{region}_"
  40. else:
  41. target = 'zh-cn'
  42. direction = "t2s_"
  43. converted = convert(content, target)
  44. # 生成智能前缀
  45. final_prefix = f"{prefix}{direction}" if prefix else f"{direction}"
  46. output_path = safe_filename(input_path, final_prefix)
  47. # 原子写入
  48. temp_path = f"{output_path}.tmp"
  49. with open(temp_path, 'w', encoding='utf-8', errors='strict') as f:
  50. f.write(converted)
  51. os.replace(temp_path, output_path)
  52. return output_path
  53. except Exception as e:
  54. if 'temp_path' in locals() and os.path.exists(temp_path):
  55. os.remove(temp_path)
  56. raise
  57. def main():
  58. parser = argparse.ArgumentParser(
  59. description='简繁转换工具(支持台湾/香港地区变体)',
  60. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  61. )
  62. parser.add_argument('filepath', help="输入文件路径")
  63. parser.add_argument('--prefix', default='',
  64. help="自定义文件名前缀")
  65. parser.add_argument('--to-traditional', action='store_true',
  66. help="启用简体转繁体模式")
  67. parser.add_argument('--region', choices=['tw', 'hk'], default='tw',
  68. help="繁体地区变体:tw(台湾,默认) 或 hk(香港)")
  69. args = parser.parse_args()
  70. input_path = Path(args.filepath)
  71. if not input_path.exists():
  72. sys.exit(f"错误:文件不存在 '{input_path}'")
  73. if args.region == 'hk' and not args.to_traditional:
  74. print("警告:--region 参数仅在启用 --to-traditional 时生效")
  75. try:
  76. result_path = convert_file(
  77. input_path,
  78. prefix=args.prefix,
  79. to_traditional=args.to_traditional,
  80. region=args.region
  81. )
  82. print(f"生成文件:{result_path}")
  83. except Exception as e:
  84. sys.exit(f"转换失败:{str(e)}")
  85. if __name__ == "__main__":
  86. main()