Files
huxiaoshuang 2f1aa67896 'init
2022-11-23 10:27:46 +08:00

50 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 百度通用翻译API,不包含词典、tts语音合成等资源如有相关需求请联系translate_api@baidu.com
# coding=utf-8
import http.client
import hashlib
import urllib
import random
import json
import time
appid = '20181013000218671' # 填写你的appid
secretKey = '3CJvgUQRitUNeo7shcTJ' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate'
# fromLang = 'auto' # 原文语种
# toLang = 'zh' # 译文语种
# toLang = 'en' # 译文语种
salt = random.randint(32768, 65536)
q = 'apple'
def transBaidu(q='hello',fromLang='',toLang=''):
# print('q---',q)
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
global myurl
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
# print (type(result))
# print ((result))
# print('翻译结果-----',result['trans_result'][0]["dst"])
time.sleep(1) #限制频率
# print(result)
return(result['trans_result'][0]["dst"])
except Exception as e:
print('error---',e)
finally:
if httpClient:
httpClient.close()