python脚本实现将代码中的中文翻译为其他语言
如果我们写的代码中带有中文的字符提示,现在要将其翻译成为其他国家的语言,在没有做多国语言配置的情况下只能自己手动复制翻译。这种机械重复性动作完全可以交给程序来做。于是我写了一个python脚本用来帮我处理源码文档。下面就是脚本代码,一共不到100行,却实实在在地解决了一个大麻烦。废话不多说,直接上代码。
import hashlib
import random
import re
import time
import requests
import os
apiurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
appid = '202*******9'
secretKey = 'jBal*******tJ'
def find_chinese(text):
regStr = ".*?([\u4E00-\u9FA5]+).*?"
aa = re.findall(regStr, text)
return aa
def translateBaidu(content, fromLang='zh', toLang='pt'):
salt = str(random.randint(32768, 65536))
sign = appid + content + salt + secretKey
sign = hashlib.md5(sign.encode("utf-8")).hexdigest()
try:
paramas = {
'appid': appid,
'q': content,
'from': fromLang,
'to': toLang,
'salt': salt,
'sign': sign
}
response = requests.get(apiurl, paramas)
jsonResponse = response.json()
dst = str(jsonResponse["trans_result"][0]["dst"])
return dst
except Exception as e:
print(e)
def text_deal(filename, fromLang='zh', toLang='pt'):
'''
读取文件,翻译成葡萄牙语,返回一个翻译好的文档的每行的list
:param filename: 翻译的文档路径
:return: 翻译好的每行的list
'''
file = open(filename, encoding="utf-8")
while 1:
lines = file.readlines(100000)
if not lines:
break
i = 0
newline = []
for line in lines:
i += 1
linea = line.lstrip()
if linea[0:2] == "//" or linea[0:4] == "<!--":
newline.append(line)
continue
chineses = find_chinese(linea)
if chineses:
print("[" + str(i) + "]: ", linea)
for c in chineses:
time.sleep(2)
translate_str = translateBaidu(c, fromLang, toLang)
line = line.replace(c, translate_str)
print(c + " ----> " + translate_str)
newline.append(line)
file.close()
return newline
files = os.listdir("./translate")
for file in files:
print("=====================")
print("正在处理文件:" + file)
newlines = text_deal("./translate/" + file, "zh", "pt")
fw = open("./translated/" + file, "a",encoding="utf-8")
for l in newlines:
fw.write(l)
fw.close()
项目目录:
|