- 前言
- 代码
- 总结
前言
找到一个英文的游戏,想玩但英文水平不行,就尝试看能不能翻译下
找到一个文件发现里面全是这种格式的
MATERIALCATEGORYFOOD = “Food”,
MATERIALCATEGORYSTONE = “Stone”,
MATERIALCATEGORYWOOD = “Wood”,
MATERIALCATEGORYCLOTH = “Cloth”,
MATERIALCATEGORYLEATHER = “Leather”,
MATERIALCATEGORYMETAL = “Metal”,
MATERIALCATEGORYPLANT = “Plant”,
MATERIALCATEGORYBONE = “Bone”,
MATERIALCATEGORYCOMPONENT = “Consumable”,
很明显要翻译的是引号里面的
代码
import requests
import httplib2
import urllib
import random
import json
from hashlib import md5
import time
def updateFile(file):
"""
替换文件中的字符串
:param file:文件名
"""
file_data = ""
with open(file, "r", encoding="utf-8") as f:
for line in f:
if "=" in line:
index = line.partition('"')
#print(index[2])
index1 = line.partition('",')
#print(index1[0])
res = []
for x in index[2]:
if x in index1[0]:
res.append(x)
if len(res) != 0:
old_str = "".join(res)
print(old_str)
new_str = baidu(old_str) # 百度翻译
print(new_str)
time.sleep(0.1)
line = line.replace(old_str, new_str) #把原来的替换成翻译的
file_data += line
with open(file,"w",encoding="utf-8") as f:
f.write(file_data)
#百度翻译
def baidu(query):
appid = 'xxxxxxxxxxxxxx' # 你的appid
secretKey = 'xxxxxxxxxxxx' # 你的密钥
httpClient = None
myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
#q = '香蕉' # 要翻译的词
fromLang = 'auto' # 翻译源语言
toLang = 'zh' # 译文语言
salt = random.randint(32768, 65536)
# 签名
sign = appid + query + str(salt) + secretKey
m1 = md5()
m1.update(sign.encode(encoding='utf-8'))
sign = m1.hexdigest()
# myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
myurl = myurl + '?q=' + urllib.parse.quote(
query) + '&from=' + fromLang + '&to=' + toLang + '&appid=' + appid + '&salt=' + str(salt) + '&sign=' + sign
try:
h = httplib2.Http('.cache')
response, content = h.request(myurl)
if response.status == 200:
# print(content.decode('utf-8'))
# print(type(content))
response = json.loads(content.decode('utf-8')) # loads将json数据加载为dict格式
# print(type(response))
# print(response["trans_result"][0]['dst'])
if "trans_result" not in response:
print(response["error_code"])
return "翻译不成功"
else:
res = response["trans_result"][0]['dst']
return res
except httplib2.ServerNotFoundError:
print("Site is Down!")```
if __name__ == '__main__':
#baidu('你好,世界') # 输出: hello
updateFile(r"D:\bcrj\pycharm_xm\Main1\cesi.txt")
总结
用的是百度翻译,appid 和 secretKey 要填你自己的APPID 和密钥。
标准版:提供基础文本翻译服务,不限字符量,QPS 为 1,免费使用(标准版服务无需认证
即可使用)。
高级版:个人开发者专享。提供基础文本翻译服务,QPS 为 10,超200万字符要收费,升了高级版要下个月后才能换成标准版,有点坑
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)