| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- #!/usr/bin/env python3
- import sys
- import os
- import argparse
- from pathlib import Path
- try:
- from zhconv import convert
- except ImportError:
- sys.exit("错误:请先安装依赖库,执行命令:pip install zhconv")
- def safe_filename(base_path, prefix='converted_'):
- """生成唯一的新文件名"""
- path = Path(base_path)
- new_stem = f"{prefix}{path.stem}"
- new_path = path.with_stem(new_stem)
-
- counter = 0
- while new_path.exists():
- counter += 1
- new_stem = f"{prefix}{counter}_{path.stem}"
- new_path = path.with_stem(new_stem)
-
- return new_path
- def detect_and_read(filepath):
- """智能检测编码并读取内容"""
- encodings = ['utf-8', 'gb18030', 'big5', 'latin-1']
- with open(filepath, 'rb') as f:
- raw_data = f.read()
-
- for enc in encodings:
- try:
- return raw_data.decode(enc)
- except UnicodeDecodeError:
- continue
- raise UnicodeDecodeError("无法识别的文件编码")
- def convert_file(input_path, prefix='', to_traditional=False, region='tw'):
- """支持多地区转换的核心函数"""
- try:
- content = detect_and_read(input_path)
-
- # 确定转换方向
- if to_traditional:
- target = 'zh-hk' if region == 'hk' else 'zh-tw'
- direction = f"s2t_{region}_"
- else:
- target = 'zh-cn'
- direction = "t2s_"
-
- converted = convert(content, target)
-
- # 生成智能前缀
- final_prefix = f"{prefix}{direction}" if prefix else f"{direction}"
-
- output_path = safe_filename(input_path, final_prefix)
-
- # 原子写入
- temp_path = f"{output_path}.tmp"
- with open(temp_path, 'w', encoding='utf-8', errors='strict') as f:
- f.write(converted)
-
- os.replace(temp_path, output_path)
- return output_path
-
- except Exception as e:
- if 'temp_path' in locals() and os.path.exists(temp_path):
- os.remove(temp_path)
- raise
- def main():
- parser = argparse.ArgumentParser(
- description='简繁转换工具(支持台湾/香港地区变体)',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter
- )
- parser.add_argument('filepath', help="输入文件路径")
- parser.add_argument('--prefix', default='',
- help="自定义文件名前缀")
- parser.add_argument('--to-traditional', action='store_true',
- help="启用简体转繁体模式")
- parser.add_argument('--region', choices=['tw', 'hk'], default='tw',
- help="繁体地区变体:tw(台湾,默认) 或 hk(香港)")
- args = parser.parse_args()
-
- input_path = Path(args.filepath)
- if not input_path.exists():
- sys.exit(f"错误:文件不存在 '{input_path}'")
-
- if args.region == 'hk' and not args.to_traditional:
- print("警告:--region 参数仅在启用 --to-traditional 时生效")
-
- try:
- result_path = convert_file(
- input_path,
- prefix=args.prefix,
- to_traditional=args.to_traditional,
- region=args.region
- )
- print(f"生成文件:{result_path}")
- except Exception as e:
- sys.exit(f"转换失败:{str(e)}")
- if __name__ == "__main__":
- main()
|