根据需求增强的完整实现:
#!/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()
python script.py input.txt --to-traditional
python script.py input.txt --to-traditional --region hk
"软件" → "軟體" (tw) / "軟件" (hk) "鼠标" → "滑鼠" (tw) / "鼠標" (hk)
输入文件:document.txt
默认转换(繁→简):t2s_document.txt 简转台繁:s2t_tw_document.txt 简转港繁:s2t_hk_document.txt 带前缀:myprefix_s2t_hk_document.txt
--to-traditional # 启用简转繁模式(默认关闭) --region [tw|hk] # 指定繁体地区变体(默认tw) --prefix # 自定义输出文件名前缀
检测无效的地区参数 处理地区参数与转换方向不匹配的情况 预防文件名重复冲突 严格编码验证
python convert.py input.txt --to-traditional
python convert.py input.txt --to-traditional --region hk --prefix "hkversion"
find . -name "*.txt" -exec python convert.py {} --to-traditional --region hk \; 转换规则对照表 简体原词 |台湾繁体| 香港繁体 软件 軟體 軟件 鼠标 滑鼠 鼠標 字节 位元組 字節 网络 網路 網絡 芯片 晶片 芯片 该实现完整保留了之前版本的安全机制,同时新增了对中文地区变体的精细控制,确保满足不同地区的用字规范需求。