import requests
import hashlib
import random
import json
def translate(text, from_lang, to_lang):
app_id = 'XXXXX'
secret_key = 'XXXXX'
salt = random.randint(32768, 65536)
sign = app_id + text + str(salt) + secret_key
sign_md5 = hashlib.md5(sign.encode()).hexdigest()
url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
params = {
'q': text,
'from': from_lang,
'to': to_lang,
'appid': app_id,
'salt': salt,
'sign': sign_md5
}
response = requests.get(url, params=params)
result = json.loads(response.text)
try:
translation = result['trans_result'][0]['dst']
return translation
except KeyError:
print("Failed to parse response!")
print(response.text)
return None
text = input("请输入要翻译的文本:")
translated_text = translate(text, 'en', 'zh')
print(translated_text)
注意
要开通百度翻译开放平台的服务