Ren'Py游戏 机器翻译实现
2020-02-19 本文已影响0人
小星star
完成了Ren'Py的机器翻译
这里写一下主要部分
建立中文滤器
def chinese_filter(s):
return generic_filter(s, chinese_transform)
判断字符串是否含有英文,含有的需要翻译,
如 (have),纯其他字符不需要,如(),不然传到百度API会返回
{u'error_code': u'54001', u'error_msg': u'Invalid Sign'}
相当于一层简单过滤
def isWords(s):
for letter in s:
if letter.isalpha():
return True
return False
这里是修改的transform
def chinese_transform(s):
"""
here is my add. use baidu API to translate english/or other language to chinese.
"""
print("---------------------------------------------------------------------")
try:
print("sentence: " + s)
except Exception, e:
print("*********Exception***********")
print(e)
return s
if isWords(s):
appid = "你的百度翻译APPID"
apiSecretKey = '你的百度翻译KEY'
httpClient = None
myurl = '/api/trans/vip/translate'
q = s
fromLang = 'en'
toLang = 'zh'
salt = random.randint(32768, 65536)
# print("sentence: " + q)
apiSign = appid+q+str(salt)+apiSecretKey
m1 = md5.new()
m1.update(apiSign)
apiSign = m1.hexdigest()
myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q.encode('utf-8'))+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+apiSign
try:
httpClient = httplib.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
response = httpClient.getresponse()
result_all = response.read()
result = json.loads(result_all)
print(result)
# real_s = result["trans_result"][0]["dst"]
return result["trans_result"][0]["dst"]
except Exception, e:
print("*********Exception***********")
print(e)
finally:
if httpClient:
httpClient.close()
return s
# print("sentence: " + s)
else:
# print("--------------------------------------------------")
return s
class Logger(object):
def __init__(self, fileN="Default.log"):
self.terminal = sys.stdout
self.log = open(fileN, "a")
# self.log = open(fileN, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger("D:\\12345.txt")
主要是
urllib.quote(q.encode('utf-8'))
注意这里q的编码
其次,注意异常捕获之后的处理
还有Logger类的使用,方便调试