在做项目的过程中,因为项目需要部署给国外用户使用,所以需要实现国际化支持,我们采用的是I18N实现国际化,这种方式类似key-value的形式,通过key查找value的值,同一个key同时对应两个值,一个是中文、一个是英文,这样就可以实现页面的中英文快速切换。我虽然有英语4级的水平,但是翻译的还是没有谷歌翻译的准确,所以我就想写个脚本实现读取已经写好i18n中文配置文件,然后调用谷歌翻译接口,翻译后直接生成英文的i18n配置文件,这样就不需要手动一个一个去翻译了。
ubuntu 18.04、python3.6.8
import json
import urllib.request
import urllib.parse
from HandleJs import Py4Js
def open_url(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
req = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(req)
data = response.read().decode('utf-8')
return data
def buildUrl(content, tk, tl):
baseUrl = 'http://translate.google.cn/translate_a/single'
baseUrl += '?client=t&'
baseUrl += 'sl=auto&'
baseUrl += 'tl=' + str(tl) + '&'
baseUrl += 'hl=zh-CN&'
baseUrl += 'dt=at&'
baseUrl += 'dt=bd&'
baseUrl += 'dt=ex&'
baseUrl += 'dt=ld&'
baseUrl += 'dt=md&'
baseUrl += 'dt=qca&'
baseUrl += 'dt=rw&'
baseUrl += 'dt=rm&'
baseUrl += 'dt=ss&'
baseUrl += 'dt=t&'
baseUrl += 'ie=UTF-8&'
baseUrl += 'oe=UTF-8&'
baseUrl += 'clearbtn=1&'
baseUrl += 'otf=1&'
baseUrl += 'pc=1&'
baseUrl += 'srcrom=0&'
baseUrl += 'ssel=0&'
baseUrl += 'tsel=0&'
baseUrl += 'kc=2&'
baseUrl += 'tk=' + str(tk) + '&'
baseUrl += 'q=' + content
return baseUrl
def translate(data, tk, tl):
#content是要翻译的内容
content = urllib.parse.quote(data[1])
url = buildUrl(content, tk, tl)
result = open_url(url)
res_json = json.loads(result)
trans_text = res_json[0][0][0]
#去除读取文字中前后的换行符和逗号及单引号或双引号
original = data[1].strip("\n").strip(",").strip("'").strip('"')
translate = trans_text.strip(",").strip("'").strip('"')
print(original + " : " + translate)
result = data[0] + ": " + trans_text + "\n"
#保存翻译后的内容到文件中
with open('/home/wuzhangwei/python/english.en.js', 'a', encoding='utf-8') as f:
f.write(result)
def main():
js = Py4Js()
#tl是要翻译的目标语种,值参照ISO 639-1标准,如果翻译成中文"zh/zh-CN简体中文"
tl = "en"
#读取需要翻译的文件
with open('/home/wuzhangwei/python/chinese.zh.js', encoding= "utf-8") as file_obj:
for line in file_obj:
data = line.split(":",1)
if len(data) == 2:
tk = js.getTk(data[1])
translate(data, tk, tl)
else:
print("Illegal row data")
if __name__ == "__main__":
main()
没有这个tk值无法正常调用谷歌翻译,这个值是用js算出来的,网上已经有大神写出来了,所以我直接拿来用了,底下有参考原文链接。
HandleJs.py
import execjs
class Py4Js():
def __init__(self):
self.ctx = execjs.compile("""
function TL(a) {
var k = "";
var b = 406644;
var b1 = 3293161072;
var jd = ".";
var $b = "+-a^+6";
var Zb = "+-3^+b+-f";
for (var e = [], f = 0, g = 0; g < a.length; g++) {
var m = a.charCodeAt(g);
128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023),
e[f++] = m >> 18 | 240,
e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
e[f++] = m >> 6 & 63 | 128),
e[f++] = m & 63 | 128)
}
a = b;
for (f = 0; f < e.length; f++) a += e[f],
a = RL(a, $b);
a = RL(a, Zb);
a ^= b1 || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1E6;
return a.toString() + jd + (a ^ b)
};
function RL(a, b) {
var t = "a";
var Yb = "+";
for (var c = 0; c < b.length - 2; c += 3) {
var d = b.charAt(c + 2),
d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
}
return a
}
""")
def getTk(self,text):
return self.ctx.call("TL",text)
因为计算tk值需要用到js库,所以python中需要引入这个包,引入步骤如下
wuzhangwei@ubuntu:~/python$ pip3 install PyExecJS
wuzhangwei@ubuntu:~/python$ python3
>>> import execjs
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'execjs']
chinese.zh.js
define({
MKT_RES_TERM_SUPPLIER:‘代理商资料管理’,
VENDOR_DATA_MANAGEMENT:‘厂商资料管理’,
MOBILE_MKT_RES_OVERAGE_MARK_CFG:“移动超库龄打标开关”,
MKT_RES_TERM_TRANSFER_MGR:‘终端资源调拨控制’,
TERMINAL_BRAND_MANAGE:‘终端品牌管理’,
MKT_RES_TERM_CONTACT:‘合同管理’,
MKT_RES_COUPON_MANAGEMENT:‘优惠券管理’,
COUPON_INST_MANAGEMENT:‘优惠券实例管理’,
MKT_STATE_MOD_RULE:‘号码状态修改规则配置’,
LOCAL_HEAD_COUNT:‘号码头统计’,
});
执行结果如下
wuzhangwei@ubuntu:~/python/myapp$ python3 main.py
Illegal row data
代理商资料管理 : Agent Data Management
厂商资料管理 : Manufacturer Data Management
移动超库龄打标开关 : Mobile Super Ageing Marking Switch
终端资源调拨控制 : Terminal resource allocation control
终端品牌管理 : Terminal brand management
合同管理 : Contract management
优惠券管理 : coupon management
优惠券实例管理 : Coupon instance management
号码状态修改规则配置 : Number status modification rule configuration
号码头统计 : Number head statistics
Illegal row data
Illegal row data
wuzhangwei@ubuntu:~/python/myapp$
MKT_RES_TERM_SUPPLIER: 'Agent Data Management',
VENDOR_DATA_MANAGEMENT: 'Manufacturer Data Management',
MOBILE_MKT_RES_OVERAGE_MARK_CFG: "Mobile Super Ageing Marking Switch",
MKT_RES_TERM_TRANSFER_MGR: 'Terminal resource allocation control',
TERMINAL_BRAND_MANAGE: 'Terminal brand management',
MKT_RES_TERM_CONTACT: 'Contract management',
MKT_RES_COUPON_MANAGEMENT: 'coupon management',
COUPON_INST_MANAGEMENT: 'Coupon instance management',
MKT_STATE_MOD_RULE: 'Number status modification rule configuration',
LOCAL_HEAD_COUNT: 'Number head statistics',
参考链接:https://blog.csdn.net/yingshukun/article/details/53470424
参考链接:https://www.jianshu.com/p/85f1d3c0dce0