今天需要做一個翻譯的工具,找到之前寫過的有道翻譯,已經不能用了,最后看到百度翻譯還不錯,不過官方版本是Python2,我需要Python3,就自己寫了一個:
# 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.clientimport hashlibimport jsonimport urllibimport 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 httplibimport md5import urllibimport random appid = '20151113000005349'secretKey = 'osubCEzlGjzvw8qdQc41' httpClient = Nonemyurl = '/api/trans/vip/translate'q = 'apple'fromLang = 'en'toLang = 'zh'salt = random.randint(32768, 65536) sign = appid+q+str(salt)+secretKeym1 = 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 efinally: if httpClient: httpClient.close()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答