import random import hashlib import requests import json import time def translate(text, lang_src, lang_dst): if not isinstance(text, str): print("text 为字符串类型") return None # 存储用户参数 query = text lang_src = lang_src lang_dst = lang_dst request_url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?' # 开发者信息 appid = '20211013000' # 写自己的 secret_key = 'umyyPojYUPKikOBk' # 写自己 salt = str(random.randint(100, 10000)) # 生成签名 sign = (appid + query + salt + secret_key).encode('utf-8') sign = hashlib.md5(sign).hexdigest() # 完整请求链接 full_request_utl = request_url + 'q=' + query + '&from=' + lang_src + '&to=' + lang_dst + '&appid=' + appid + '&salt=' + salt + '&sign=' + sign # 发送翻译请求 response = requests.get(full_request_utl) # 解析响应数据 response_json = response.content.decode('utf-8') response_dict = json.loads(response_json) if response_dict.get('error_code'): print('错误码:', response_dict['error_code'], '错误描述:', response_dict['error_msg']) return None return response_dict['trans_result'][0]['dst'] if __name__ == '__main__': sentence = translate('我爱你中国', 'zh', 'kor') print(sentence) time.sleep(1) print('-' * 30) sentence = translate('我爱你,王老师', 'zh', 'en') print(sentence)
需要部署在服务器端,在百度开发中心设置请求的 IP 地址。