由于百度通用翻译官方只有pythone2版本的demo,所以,你懂的
首先需要申请百度开发者账号,创建app
拿到appid以及secretkey
http://api.fanyi.baidu.com/api/trans/product/apidoc
代码:
# -*- coding:utf-8 -*-
import http.client
import hashlib
import urllib.request
import random
import json
appid = '' #你的appid
secretKey = '' #你的密钥
class BaiDu(object):
def __init__(self):
self.httpClient = None
self.myurl = '/api/trans/vip/translate'
def trans(self,q = 'apple'):
fromLang = 'zh'
toLang = 'en'
salt = random.randint(32768, 65536)
sign = appid + q + str(salt) + secretKey
m1 = hashlib.md5()
b = sign.encode(encoding='utf-8')
m1.update(b)
sign = m1.hexdigest()
self.myurl = self.myurl + '?appid=' + appid + '&q=' + urllib.request.quote(
q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
try:
self.httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
self.httpClient.request('GET', self.myurl)
# response是HTTPResponse对象
response = self.httpClient.getresponse()
w = response.read()
r = json.loads(w)
#print(r)
content = r['trans_result']
# print(content)
return (content[0]['dst'])
except Exception as e:
print(e)
finally:
if self.httpClient:
self.httpClient.close()
if __name__ == '__main__':
w = BaiDu()
print(w.trans("今天是个好日子"))
效果: