def make_md5(s, encoding='utf-8'):
return md5(s.encode(encoding)).hexdigest()
def get_trans_result(query, appid, appkey, from_lang='en', to_lang='zh'):
endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path
salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
r = requests.post(url, params=payload, headers=headers)
result = r.json(strict=False)
# print(result)
result = result.get('trans_result')
# print(result)
if not result:
print('没有翻译结果:', query)
print('>>>>>', r.json())
res = [obj['dst'] for obj in result]
trans_result = '\n'.join(res)
return trans_result
1.注册账号:百度翻译开放平台
2.完成后打开开发者中心 百度翻译开放平台,点立即开通,在总览-我的服务中,开通通用文本翻译,选择高级版(每月100万字符免费调用量)
3.然后在开发者中心-开发者信息中百度翻译开放平台,获取appid
4.就可以使用上述脚本啦