lupdate_all.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # 刷新所有翻译文本文件 .ts
  2. import os
  3. import sys
  4. import xml.etree.ElementTree as ET
  5. LangList = [
  6. "en_US",
  7. "zh_TW",
  8. "ja_JP",
  9. "fr_FR",
  10. "pt",
  11. # "nb_NO",
  12. # "it_IT",
  13. # "es_ES",
  14. # "de_DE",
  15. # "ko_KR",
  16. # "ru_RU",
  17. # "pt_BR",
  18. ]
  19. working = os.path.dirname(os.path.abspath(__file__)) # 工作目录
  20. os.chdir(working)
  21. # 1. 扫描qml文件,生成 en_US.ts
  22. for l in LangList:
  23. cmd = f'''lupdate.exe \
  24. "../../UmiOCR-data/qt_res/qml" \
  25. -recursive \
  26. -no-obsolete \
  27. -source-language "zh_CN" \
  28. -target-language "{l}" \
  29. -ts "release/{l}.ts"'''
  30. os.system(cmd)
  31. sys.exit() # Py翻译的部分 待定
  32. # 2. 扫描py文件,生成 en_US_2.ts
  33. def find_files(path, end=".py"):
  34. path = os.path.abspath(path)
  35. files_list = []
  36. for root, dirs, files in os.walk(path):
  37. # if "__pycache__"
  38. for file in files:
  39. if file.endswith(end):
  40. f = os.path.join(root, file)
  41. f = os.path.relpath(f, os.path.dirname(__file__))
  42. files_list.append(f) # 使用相对路径,避免父路径的编码问题
  43. return files_list
  44. input_files = find_files("../../UmiOCR-data/py_src")
  45. input_str = "\\\n".join(input_files)
  46. output_str = "release/" + "_2.ts\\\nrelease/".join(LangList) + "_2.ts"
  47. temp_file = "temp.pro" # 临时指令文件,用完删除
  48. pro_str = f"""
  49. CODECFORTR = UTF-8
  50. CODECFORSRC = UTF-8
  51. SOURCES = {input_str}
  52. TRANSLATIONS = {output_str}
  53. """
  54. with open(temp_file, "w", encoding="utf-8") as f:
  55. f.write(pro_str)
  56. cmd = f"pyside2-lupdate.exe {temp_file}"
  57. os.system(cmd)
  58. print(output_str)
  59. os.remove(temp_file)
  60. # 3. 合并 en_US.ts 、 en_US_2.ts
  61. for l in LangList:
  62. path_1 = f"release/{l}.ts"
  63. path_2 = f"release/{l}_2.ts"
  64. with open(path_2, "r", encoding="utf-8") as file:
  65. lines_2 = file.readlines()
  66. # py部分 无需翻译
  67. if len(lines_2) < 10:
  68. print(f"无需合并:{path_1}")
  69. continue
  70. # py部分 需合并
  71. # 解析xml
  72. tree_1 = ET.parse(path_1)
  73. root_1 = tree_1.getroot()
  74. root_2 = ET.parse(path_2).getroot()
  75. context_2 = root_2.findall("context")
  76. # 建立一个字典,存放所有 context
  77. context_dict = {c.find("name").text: c for c in root_1.findall("context")}
  78. # 遍历2,追加进字典
  79. # # 将2的context并入1
  80. for c2 in root_2.findall("context"):
  81. name = c2.find("name").text
  82. if name in context_dict:
  83. c1 = context_dict[name]
  84. for message_2 in c2.findall("message"):
  85. c1.append(message_2)
  86. else:
  87. root_1.append(c2) # TODO: 正确性未验证
  88. # TODO: 保存时检查缩进格式
  89. tree_1.write(path_1, encoding="utf-8", xml_declaration=True)
  90. print(f"合并:{path_1}")
  91. os.remove(path_2)