方法
from http.client import HTTPConnection
from urllib.parse import quote
from random import randint
from hashlib import md5
from json import loads
from time import sleep
def BaiduFanyi(input_text):
# 因为百度限制每秒1次访问,故此处静默1.5s,可适当调整
sleep(1.5)
# 准备工作
appid = '20008899554321678' # 此处替换为自己的百度翻译appid
secretKey = 'fRbVG3UqP2_CkgwSzJHM' # 此处替换为自己的百度翻译密钥
url = '/api/trans/vip/translate'
fromLang = 'auto' # 源语言,此处可进行替换,auto是自动,en是英语,zh是中文
toLang = 'zh' # 目标语言,此处可进行替换
# 开始翻译
httpClient = None
salt = randint(3276, 65536)
sign = appid + input_text + str(salt) + secretKey
sign = md5(sign.encode()).hexdigest()
url = url \
+ '?appid=' + appid \
+ '&q=' + quote(input_text) \
+ '&from=' + fromLang \
+ '&to=' + toLang \
+ '&salt=' + str(salt) \
+ '&sign=' + sign
output_text = ""
try:
httpClient = HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', url)
response = httpClient.getresponse()
result_response = response.read().decode('utf-8')
result_json = loads(result_response)
# 读取百度翻译返回的结果
output_text = ""
for n in range(0, len(result_json['trans_result'])):
output_text = output_text + result_json['trans_result'][n]['dst'] + "\n"
return output_text
except Exception as e:
return "翻译出错"
finally:
if httpClient:
httpClient.close()
if __name__ == "__main__":
# 百度翻译是支持多行文本的,只要你处理好换行关系,多少行文本都没问题
# 但是请注意,百度限制了每次最多提交5000个字符(包括空格和标点符号),超过的部分会被抹去
input_text = "Hello.\nI'm Bear Xiong.\nNice to meet you."
output_text = BaiduFanyi(input_text)
print(output_text)
后记
曾几何时,我有一份「 英文文献信息.xlsx 」,里面有着2万4千余条需要进行初筛的文献记录,净是英文。那是一段令人痛苦的经历……
最后补充一句:
别想了,上面的 appid 和 密钥 是我乱写的,自己申请去