百度翻译API翻译Qt LinguistTools的ts文件
# coding=utf-8
import http.client
import hashlib
import urllib
import random
import json
import xml.etree.ElementTree as ET
import time
appid = '' # 填写你的appid
secretKey = '' # 填写你的密钥
def translate_text(text):
httpClient = None
myurl = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
result = ''
fromLang = 'zh' # 原文语种
toLang = 'en' # 译文语种
salt = random.randint(32768, 65536)
#text = '苹果'
sign = appid + text + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
text) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
print(result)
result = result['trans_result'][0]['dst']
return result;
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()
def translate_ts_file(input_file, output_file):
# 解析 TS 文件
tree = ET.parse(input_file)
root = tree.getroot()
# 遍历所有的消息
for context in root.findall('context'):
for message in context.findall('message'):
source = message.find('source')
if source is not None:
text_to_translate = source.text
if text_to_translate:
print(f'Translating: {text_to_translate}')
translated_text = translate_text(text_to_translate)
translation = message.find('translation')
if translation is None:
translation = ET.SubElement(message, 'translation', type="unfinished")
else:
translation.set('type', 'finished') # 更新 type 属性
translation.text = translated_text
time.sleep(1);
# 写入翻译后的 TS 文件
tree.write(output_file, encoding='utf-8', xml_declaration=True)
print(f'Translated TS file saved as: {output_file}')
if __name__ == "__main__":
filename = input("请输入ts文件名(en):")
translate_ts_file(filename, filename)
由于API限制访问频率,所以加了sleep
推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt