Python通過調用有道翻譯api實現(xiàn)翻譯功能示例
本文實例講述了Python通過調用有道翻譯api實現(xiàn)翻譯功能。分享給大家供大家參考,具體如下:
通過調用有道翻譯的api,實現(xiàn)中譯英、其他語言譯中文
Python代碼:
# coding=utf-8 import urllib import urllib2 import json import time import hashlib class YouDaoFanyi: def __init__(self, appKey, appSecret): self.url = 'https://openapi.youdao.com/api/' self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36", } self.appKey = appKey # 應用id self.appSecret = appSecret # 應用密鑰 self.langFrom = 'auto' # 翻譯前文字語言,auto為自動檢查 self.langTo = 'auto' # 翻譯后文字語言,auto為自動檢查 def getUrlEncodedData(self, queryText): ''' 將數(shù)據(jù)url編碼 :param queryText: 待翻譯的文字 :return: 返回url編碼過的數(shù)據(jù) ''' salt = str(int(round(time.time() * 1000))) # 產(chǎn)生隨機數(shù) ,其實固定值也可以,不如"2" sign_str = self.appKey + queryText + salt + self.appSecret sign = hashlib.md5(sign_str).hexdigest() payload = { 'q': queryText, 'from': self.langFrom, 'to': self.langTo, 'appKey': self.appKey, 'salt': salt, 'sign': sign } # 注意是get請求,不是請求 data = urllib.urlencode(payload) return data def parseHtml(self, html): ''' 解析頁面,輸出翻譯結果 :param html: 翻譯返回的頁面內容 :return: None ''' data = json.loads(html) print '-' * 10 translationResult = data['translation'] if isinstance(translationResult, list): translationResult = translationResult[0] print translationResult if "basic" in data: youdaoResult = "\n".join(data['basic']['explains']) print '有道詞典結果' print youdaoResult print '-' * 10 def translate(self, queryText): data = self.getUrlEncodedData(queryText) # 獲取url編碼過的數(shù)據(jù) target_url = self.url + '?' + data # 構造目標url request = urllib2.Request(target_url, headers=self.headers) # 構造請求 response = urllib2.urlopen(request) # 發(fā)送請求 self.parseHtml(response.read()) # 解析,顯示翻譯結果 if __name__ == "__main__": appKey = '應用id' # 應用id appSecret = '應用密鑰' # 應用密鑰 fanyi = YouDaoFanyi(appKey, appSecret) while True: queryText = raw_input("請輸入你好翻譯的文字[Q|quit退出]: ").strip() if queryText in ['Q', 'quit']: break fanyi.translate(queryText)
關于有道翻譯api的詳細說明可參考其官網(wǎng):http://ai.youdao.com/docs/api.html
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python Socket編程技巧總結》、《Python URL操作技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python區(qū)塊鏈實現(xiàn)簡版網(wǎng)絡
這篇文章主要為大家介紹了python區(qū)塊鏈實現(xiàn)簡版網(wǎng)絡的詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05Python 解析pymysql模塊操作數(shù)據(jù)庫的方法
這篇文章主要介紹了Python 解析pymysql模塊操作數(shù)據(jù)庫的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02