前言
在做多语言文件时,大部分多语言是翻译软件翻译的,可能翻译的不准确,或者多语言文件有缺失的情况。这时候可以选择一个多语言文件为基础(base)文件,然后将多语言文件生成一个对比的csv文件,做成在线表格,方便校验和修改翻译的值。
代码
import os
import csv
from datetime import datetime
def decode_unicode_escape(text):
"""
将Unicode转义序列(如\u4e2d\u6587)转换为实际字符
"""
try:
# 使用encode-decode方法处理Unicode转义序列
if '\\u' in text:
# 先编码为latin-1,再解码为unicode_escape,最后解码为utf-8
return text.encode('latin-1', 'backslashreplace').decode('unicode_escape')
except:
pass
return text
def read_properties_file(file_path):
"""
读取properties文件,返回key-value字典,并确保中文字符正确显示
"""
properties = {}
try:
with open(file_path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
# 跳过空行和注释行
if not line or line.startswith('#') or line.startswith('!'):
continue
# 处理key-value对
if '=' in line:
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
# 解码Unicode转义序列
value = decode_unicode_escape(value)
properties[key] = value
except UnicodeDecodeError:
# 如果utf-8解码失败,尝试使用latin-1
try:
with open(file_path, 'r', encoding='latin-1') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith('#') or line.startswith('!'):
continue
if '=' in line:
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
# 解码Unicode转义序列
value = decode_unicode_escape(value)
properties[key] = value
except Exception as e:
print(f"读取文件 {file_path} 时出错(行 {line_num}): {e}")
except Exception as e:
print(f"读取文件 {file_path} 时出错: {e}")
return properties
def generate_i18n_csv(directory, project_name, i18n_prefix="i18n", output_csv=None):
"""
读取指定目录下的i18n文件并生成CSV比较文件
"""
# 文件列表定义
files = {
'base': os.path.join(directory, f'{i18n_prefix}_en_US.properties'),
'de': os.path.join(directory, f'{i18n_prefix}_de_DE.properties'),
'fr_FR': os.path.join(directory, f'{i18n_prefix}_fr_FR.properties'),
'es_ES': os.path.join(directory, f'{i18n_prefix}_es_ES.properties'),
'zh_CN': os.path.join(directory, f'{i18n_prefix}_zh_CN.properties'),
'zh_HK': os.path.join(directory, f'{i18n_prefix}_zh_HK.properties')
}
# 读取所有文件
properties_dict = {}
for name, file_path in files.items():
if os.path.exists(file_path):
properties_dict[name] = read_properties_file(file_path)
print(f"读取 {file_path} 成功,包含 {len(properties_dict[name])} 个key")
else:
print(f"警告: 文件 {file_path} 不存在")
properties_dict[name] = {}
# 以基准文件的key为基准
if 'base' not in properties_dict or not properties_dict['base']:
print("错误: 未找到有效的i18n.properties基准文件")
return False
# 获取所有key并排序
all_keys = sorted(properties_dict['base'].keys())
print(f"总共获取到 {len(all_keys)} 个基准key")
# 确定输出CSV文件路径 - 使用桌面csv文件夹
if not output_csv:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
output_dir = r"C:\Users\xp\Desktop\csv"
# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)
output_csv = os.path.join(output_dir, f'i18n_comparison_{timestamp}.csv')
# 写入CSV文件
try:
with open(output_csv, 'w', newline='', encoding='utf-8-sig') as csvfile:
# 定义CSV头部 - 最前面添加项目名称列,为每种语言添加修改后值列
fieldnames = ['项目名称', 'key', '基准值(i18n)', '德语(de)', '德语修改后值', '法语(fr_FR)', '法语修改后值', '西班牙语(es_ES)', '西班牙语修改后值', '简体中文(zh_CN)', '简体中文修改后值', '繁体中文(zh_HK)', '繁体中文修改后值']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# 写入头部
writer.writeheader()
# 写入每一行数据
for key in all_keys:
row = {
'项目名称': project_name, # 添加项目名称
'key': key,
'基准值(i18n)': properties_dict['base'].get(key, ''),
'德语(de)': properties_dict['de'].get(key, ''),
'德语修改后值': '', # 初始为空字符串
'法语(fr_FR)': properties_dict['fr_FR'].get(key, ''),
'法语修改后值': '', # 初始为空字符串
'西班牙语(es_ES)': properties_dict['es_ES'].get(key, ''),
'西班牙语修改后值': '', # 初始为空字符串
'简体中文(zh_CN)': properties_dict['zh_CN'].get(key, ''),
'简体中文修改后值': '', # 初始为空字符串
'繁体中文(zh_HK)': properties_dict['zh_HK'].get(key, ''),
'繁体中文修改后值': '' # 初始为空字符串
}
writer.writerow(row)
print(f"CSV文件已成功生成: {output_csv}")
return True
except Exception as e:
print(f"生成CSV文件时出错: {e}")
return False
def main():
"""
主函数,使用固定路径字符串执行转换
"""
# i18n文件前缀变量
i18n_prefix = "i18ne"
project_name = "parent" # 直接使用目录中的项目名称部分
# 使用固定路径字符串
directory = r"D:\work\src\xp-ass-parent\xp-ass-starter-file\src\main\resources" # 这里可以修改为你需要的目录路径
print("=== i18n资源文件比较工具 ===")
print("此工具将读取指定目录下的i18n资源文件并生成比较CSV文件")
if not os.path.isdir(directory):
print(f"错误: 目录 '{directory}' 不存在")
return
# 从目录路径中提取项目名称 (使用目录结构中的项目标识)
print(f"\n正在处理目录: {directory}")
print(f"项目名称: {project_name}")
print(f"i18n文件前缀: {i18n_prefix}")
# 生成CSV文件
success = generate_i18n_csv(directory, project_name, i18n_prefix)
if success:
print("\n操作完成!")
else:
print("\n操作失败,请检查错误信息")
if __name__ == "__main__":
main()
主要变量
output_dir = r"C:\Users\xp\Desktop\csv"
# i18n文件前缀变量
i18n_prefix = "i18n-xp-ass-starter-file"
project_name = "xp-ass-parent" # 直接使用目录中的项目名称部分
# 使用固定路径字符串
directory = r"D:\work\src\xp-ass-parent\xp-ass-starter-file\src\main\resources" # 这里可以修改为你需要的目录路径
3323

被折叠的 条评论
为什么被折叠?



