-
百度翻译api官方网址:
https://fanyi-api.baidu.com/
-
首先注册得到APPID和密钥。
-
参数:
输入参数
输出参数
-
官方DEMO
#百度通用翻译API,不包含词典、tts语音合成等资源,如有相关需求请联系translate_api@baidu.com
# coding=utf-8
import http.client
import hashlib
import urllib
import random
import json
appid = '' # 填写你的appid
secretKey = '' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate'
fromLang = 'en' #原文语种
toLang = 'zh' #译文语种
salt = random.randint(32768, 65536)
q= 'apple'
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
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('翻译::')
print (result)
except Exception as e:
print (e)
finally:
if httpClient:
httpClient.close()
需要填写本人的appid和密钥。
q为需要翻译的内容,翻译结果在result中
输出结果为:
{'from': 'en', 'to': 'zh', 'trans_result': [{'src': 'apple', 'dst': '苹果'}]}