您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)怎么在python3中調(diào)用百度翻譯API實現(xiàn)實時翻譯,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
# coding: utf8 ''' @Author: LCY @Contact: lchuanyong@126.com @blog: http://http://blog.csdn.net/lcyong_ @Date: 2018-01-15 @Time: 19:19 說明: appid和secretKey為百度翻譯文檔中自帶的,需要切換為自己的 python2和python3部分庫名稱更改對應(yīng)如下: httplib ----> http.client md5 ----> hashlib.md5 urllib.quote ----> urllib.parse.quote 官方鏈接: http://api.fanyi.baidu.com/api/trans/product/index ''' import http.client import hashlib import json import urllib import random def baidu_translate(content): appid = '20151113000005349' secretKey = 'osubCEzlGjzvw8qdQc41' httpClient = None myurl = '/api/trans/vip/translate' q = content fromLang = 'zh' # 源語言 toLang = 'jp' # 翻譯后的語言 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) # response是HTTPResponse對象 response = httpClient.getresponse() jsonResponse = response.read().decode("utf-8")# 獲得返回的結(jié)果,結(jié)果為json格式 js = json.loads(jsonResponse) # 將json格式的結(jié)果轉(zhuǎn)換字典結(jié)構(gòu) dst = str(js["trans_result"][0]["dst"]) # 取得翻譯后的文本結(jié)果 print(dst) # 打印結(jié)果 except Exception as e: print(e) finally: if httpClient: httpClient.close() if __name__ == '__main__': while True: print("請輸入要翻譯的內(nèi)容,如果退出輸入q") content = input() if (content == 'q'): break baidu_translate(content)
官方版本:
#/usr/bin/env python #coding=utf8 import httplib import md5 import urllib import random appid = '20151113000005349' secretKey = 'osubCEzlGjzvw8qdQc41' httpClient = None myurl = '/api/trans/vip/translate' q = 'apple' fromLang = 'en' toLang = 'zh' salt = random.randint(32768, 65536) sign = appid+q+str(salt)+secretKey m1 = md5.new() m1.update(sign) sign = m1.hexdigest() myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign try: httpClient = httplib.HTTPConnection('api.fanyi.baidu.com') httpClient.request('GET', myurl) #response是HTTPResponse對象 response = httpClient.getresponse() print response.read() except Exception, e: print e finally: if httpClient: httpClient.close()
以上就是怎么在python3中調(diào)用百度翻譯API實現(xiàn)實時翻譯,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。