Baidu Translation API Code
作者:XD / 发表: 2023年7月25日 03:16 / 更新: 2023年7月25日 03:16 / 编程笔记 / 阅读量:881
Baidu Translation API Code
import requests
import hashlib
import random
def translate_text(text, from_lang='en', to_lang='zh'):
app_id = '202300xx' # update your app_id and app_key
app_key = 'OFxx' # app_id and app_key can be applied from https://cloud.baidu.com/
url = "http://api.fanyi.baidu.com/api/trans/vip/translate"
salt = random.randint(32768, 65536)
sign = app_id + text + str(salt) + app_key
sign = hashlib.md5(sign.encode()).hexdigest()
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': app_id, 'q': text, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
response = requests.post(url, params=payload, headers=headers)
response_json = response.json()
return response_json['trans_result'][0]['dst']
相关标签