百度翻译接口调用实例
程序员文章站
2022-03-31 11:40:33
百度接口启用地址:https://api.fanyi.baidu.com/ 创建自己的翻译项目,并注意保留APPID和密钥# 中文翻译成英文def translate_t(myurl,httpClient,q_t): fromLang = 'auto' #原文语种[自动检测] toLang = 'en' #译文语种[英语] salt = random.randint(32768, 65536) sign = appid + q_t + str(salt) +....
百度接口启用地址:https://api.fanyi.baidu.com/ 创建自己的翻译项目,并注意保留APPID和密钥
# 中文翻译成英文
def translate_t(myurl,httpClient,q_t):
fromLang = 'auto' #原文语种[自动检测]
toLang = 'en' #译文语种[英语]
salt = random.randint(32768, 65536)
sign = appid + q_t + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl1 = myurl + '?appid=' + appid + '&q=' + parse.quote(q_t) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl1)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
jg = (result['trans_result'][0]['dst'])
except Exception as e:
print(e)
jg = '接口请求出错'
finally:
if httpClient:
httpClient.close()
return jg
# 英文翻译成中文
def translate_f(myurl, httpClient,q_f):
fromLang = 'auto' # 原文语种[自动检测]
toLang = 'zh' # 译文语种[中文]
salt = random.randint(32768, 65536)
sign = appid + q_f + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl1 = myurl + '?appid=' + appid + '&q=' + parse.quote(q_f) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl1)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
jg = (result['trans_result'][0]['dst'])
except Exception as e:
print(e)
jg = '接口请求出错'
finally:
if httpClient:
httpClient.close()
return jg
if __name__ == '__main__':
i = '' # 需要翻译的字符串
if 'img' not in i and i != '':
appid = '20200707000514536' # 填写你的appid
secretKey = '2T7OTcmi3V2slOlGYQfR' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate'
q_t = i.replace('<p>','')
q_f = translate_t(myurl,httpClient,q_t)
print(q_f)
sleep(5)
jg = translate_f(myurl,httpClient,q_f)
sleep(5)
print('<p>' + jg)
news.append('<p>' + jg)
else:
news.append(i)
本文地址:https://blog.csdn.net/mjp_erhuo/article/details/107191781