您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關怎么在python3中調用百度翻譯API實現實時翻譯,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
# 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部分庫名稱更改對應如下: 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")# 獲得返回的結果,結果為json格式 js = json.loads(jsonResponse) # 將json格式的結果轉換字典結構 dst = str(js["trans_result"][0]["dst"]) # 取得翻譯后的文本結果 print(dst) # 打印結果 except Exception as e: print(e) finally: if httpClient: httpClient.close() if __name__ == '__main__': while True: print("請輸入要翻譯的內容,如果退出輸入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中調用百度翻譯API實現實時翻譯,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。