天天看点

Python3 百度翻译api调用

2018/10/24~3

学习英语,当然得是要四六级的单词本呀,所以前面爬了这几年的四六级的考试题,拆成了一个单词本,但是单词本没中文翻译岂不是很不爽,这就要请求翻译了呀,但是百度翻译api提供的是python2的模板。。。

这里记录一下修改后python3的使用模板

#翻译
#/usr/bin/env python
#coding=utf8
import http.client
import hashlib
import urllib.request
import random
import json

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

httpClient = None
#myurl = '/api/trans/vip/translate'
myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
#输入的单词
q = 'apple'

#输入英文输出中文
fromLang = 'en'
toLang = 'zh'
salt = random.randint(32768, 65536)
sign = appid+q+str(salt)+secretKey
m1 = hashlib.new('md5')
m1.update(sign.encode('utf-8'))
sign=m1.hexdigest()
#m1 = hashlib.new('md5',sign).hexdigest()
#m1.update(sign)
#sign = m1.hexdigest()
myurl = myurl+'?q='+urllib.request.quote(q)+'&from='+fromLang+'&to='+toLang+'&appid='+appid+'&salt='+str(salt)+'&sign='+sign
try:
    httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
    httpClient.request('GET', myurl)
    #response是HTTPResponse对象
    response = httpClient.getresponse()
    result=response.read()
    
    data = json.loads(result)
    wordMean=data['trans_result'][0]['dst']
    print(wordMean)

except Exception as e:
    print(e)
finally:
    if httpClient:
        httpClient.close()
           

一次发送多个单词的方式。。。还是见帮助文档吧,稍微改一下就行了