?由于百度通用翻譯官方只有pythone2版本的demo,所以,你懂的
首先需要申請百度開發(fā)者賬號,創(chuàng)建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("今天是個好日子"))
效果:
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
