qt翻译
这两天做qt翻译功能,用到了AI工具。把过程记录一下。
- 在 CMake + Qt5 里正确配置翻译: Qt5LinguistTools + qt5_add_translation,只把 .qm 加到 target_sources。
- 用命令行 lupdate 生成 ts 文件,解决 Qt Creator 对 CMake 工程不自动传 -ts 的问题。
- 用 Python + 百度翻译 API 批量翻译 .ts,自动把中文转成英文,再由 CMake 生成 .qm。
一、CMake中添加
# 翻译文件(Qt 5.15.2,.ts 自动生成 .qm) set(TS_FILES ${SYS_SRC_PATH}/scada/reporttoolsdll/reporttoolsdll_en.ts ) qt5_add_translation(QM_FILES ${TS_FILES}) target_sources(${PROJECT_NAME} PRIVATE ${QM_FILES} )
二、实际上可以在qtcreator上直接生成ts文件和qm文件。或者直接在ts所在文件夹用命令行:"d:\Qt\5.15.2\msvc2019_64\bin\lupdate.exe" . -recursive -ts reporttoolsdll_en.ts
三、关于大量的翻译,可以调用百度翻译接口。
python调用:
1 import os 2 import random 3 import hashlib 4 import requests 5 import xml.etree.ElementTree as ET 6 7 TS_PATH = r"e:\src\pms1000\pms1000_v2.0\src\scada\reporttoolsdll\reporttoolsdll_en.ts" 8 BACKUP_PATH = TS_PATH + ".bak" 9 10 APP_ID = "myid" # 用 从百度申请的那一套 11 SECRET_KEY = "mykey" 12 13 # ================== 你已经验证通过的翻译函数 ================== 14 15 def translate_text(app_id, secret_key, text, from_lang='zh', to_lang='en'): 16 """调用百度翻译,把 text 从 from_lang 翻到 to_lang""" 17 if not text: 18 return text 19 20 salt = str(random.randint(32768, 65536)) 21 # 注意:签名前 q 不进行 URL encode 22 sign_str = f"{app_id}{text}{salt}{secret_key}" 23 sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest() 24 25 params = { 26 'q': text, # 这里 requests 会自动处理 URL encode 27 'from': from_lang, 28 'to': to_lang, 29 'appid': app_id, 30 'salt': salt, 31 'sign': sign 32 } 33 34 resp = requests.get('https://fanyi-api.baidu.com/api/trans/vip/translate', 35 params=params, timeout=10) 36 data = resp.json() 37 if 'error_code' in data: 38 # 出错时返回原文,避免打断整个脚本 39 print(f"[BAIDU ERROR] {data.get('error_code')} for: {text}") 40 return text 41 42 # trans_result 可能有多段,这里简单拼接 43 return "".join(item["dst"] for item in data.get("trans_result", [])) 44 45 # ================== TS 批量处理逻辑 ================== 46 47 def is_chinese(s: str) -> bool: 48 return any('\u4e00' <= ch <= '\u9fff' for ch in s) 49 50 def main(): 51 if not os.path.exists(TS_PATH): 52 print(f"TS file not found: {TS_PATH}") 53 return 54 55 # 先备份 56 if not os.path.exists(BACKUP_PATH): 57 import shutil 58 shutil.copyfile(TS_PATH, BACKUP_PATH) 59 print(f"Backup created: {BACKUP_PATH}") 60 61 tree = ET.parse(TS_PATH) 62 root = tree.getroot() 63 64 count_auto = 0 65 count_skip = 0 66 67 for ctx in root.findall("context"): 68 for msg in ctx.findall("message"): 69 source = msg.find("source") 70 if source is None or not source.text: 71 continue 72 73 src_text = source.text.strip() 74 if not src_text: 75 continue 76 77 translation = msg.find("translation") 78 79 # 已有非 unfinished 的翻译,跳过 80 if translation is not None and translation.text and translation.get("type") != "unfinished": 81 count_skip += 1 82 continue 83 84 # 没有 translation 节点就创建一个 85 if translation is None: 86 translation = ET.SubElement(msg, "translation") 87 88 # 源文本不是中文(多半已是英文/符号),直接复制 89 if not is_chinese(src_text): 90 translation.text = src_text 91 translation.attrib.pop("type", None) 92 count_skip += 1 93 continue 94 95 # 中文 -> 英文(用你已经验证过的函数) 96 en_text = translate_text(APP_ID, SECRET_KEY, src_text, 'zh', 'en') 97 translation.text = en_text 98 translation.attrib.pop("type", None) 99 count_auto += 1 100 print(f"[AUTO] {src_text} -> {en_text}") 101 102 tree.write(TS_PATH, encoding="utf-8") 103 print(f"Done. Auto translated {count_auto} entries, skipped {count_skip} entries.") 104 105 if __name__ == "__main__": 106 main()
直接调用上面的1111.py文件(注意先cd到1111.py所在文件夹):py 1111.py,并观察结果

百度开通通用文本翻译



浙公网安备 33010602011771号