Python 百度翻译接口调用

发表时间:2019-12-18

测试环境:

python3.7

完整代码:

直接调用百度翻译官方接口,不需要使用爬虫

import random
import hashlib
import urllib
import http.client
import json


content=input('输入需要翻译的内容:')
# 百度翻译
def baidu_translation(content):
appid = '20190524000*****' # 你的appid
secretKey = 'TFO7sVRJaI*****' # 你的密钥
httpClient = None
myurl = '/api/trans/vip/translate'
q = content
fromLang = 'en'
toLang = 'zh'
salt = random.randint(32768, 65536)
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)

# responseHTTPResponse对象
response = httpClient.getresponse()
jsonResponse = response.read().decode("utf-8") # 获得返回的结果,结果为json格式
js = json.loads(jsonResponse) # json格式的结果转换字典结构
dst = str(js["trans_result"][0]["dst"]) # 取得翻译后的文本结果
print(dst)
return (dst) # 打印结果
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()

if __name__ == '__main__':
baidu_translation(content)

注意:

这里需要输入你自己的appid和secretKey,注册地址:http://api.fanyi.baidu.com/api/trans/product/index,每月好像是免费五万个单词

appid = '20190524000301561'  # 你的appid
secretKey = 'TFO7sVRJaIFzcBcnEUQx' # 你的密钥


运行效果:

Rec 0002.gif


Python Free

邮箱:417803890@qq.com
QQ:417803890

皖ICP备19001818号
© 2019 copyright www.pythonf.cn - All rights reserved

微信扫一扫关注公众号:

联系方式

Python Free