-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathandroid_strings_translate.py
executable file
·81 lines (68 loc) · 2.4 KB
/
android_strings_translate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# /usr/bin/env android_strings_translate
# coding=utf8
import http.client
from hashlib import md5
import urllib
import random
from xml.etree import ElementTree as ET
import json as js
import os
from configparser import ConfigParser
import logging
import time
config = ConfigParser()
config.read('config.ini', encoding='UTF-8')
appid = config.get("config", "appid") # 你的appid
secretKey = config.get("config", "secretKey") # 你的密钥
filePath = config.get("config", "filePath") # 设置strings.xml的路径
httpClient = None
myurl = '/api/trans/vip/translate'
fromLang = 'zh'
toLang = 'cht'
salt = random.randint(32768, 65536)
ET.register_namespace('tools', "http://schemas.android.com/tools")
tree = ET.parse(filePath)
root = tree.getroot()
result = True
for child in root:
if child.text is None:
logging.warning(child.attrib["name"] + " value is empty!")
continue
sign = appid + child.text + str(salt) + secretKey
m1 = md5(sign.encode("utf-8"))
sign = m1.hexdigest()
requestUrl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
child.text) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
print("requestUrl", requestUrl)
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', requestUrl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result = response.read()
print("response", result)
result.decode('utf-8')
print("result", result)
x = js.loads(result)
trans_result = x["trans_result"]
print("src:", trans_result[0]["src"], "dst:", trans_result[0]["dst"])
child.text = trans_result[0]["dst"]
time.sleep(3)
except Exception as e:
result = False
print("请求百度翻译接口失败!", e.args)
print("翻译失败-------", child.text)
finally:
if httpClient:
httpClient.close()
if result is False:
print("存在翻译失败的字符串, 退出程序!")
exec (0)
xml_str = '<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(root, method='xml', encoding="UTF-8").decode(
"UTF-8") # 避免声明是单引号
print(xml_str)
targetFile = os.path.dirname(filePath) + "/strings_" + toLang + ".xml"
with open(targetFile, 'w') as xml_file:
xml_file.write(xml_str)
print("-----XML字段更新完毕!")