本文實(shí)例講述了Python通過(guò)調(diào)用有道翻譯api實(shí)現(xiàn)翻譯功能。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)公司專(zhuān)業(yè)為企業(yè)提供衡水網(wǎng)站建設(shè)、衡水做網(wǎng)站、衡水網(wǎng)站設(shè)計(jì)、衡水網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、衡水企業(yè)網(wǎng)站模板建站服務(wù),十余年衡水做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。通過(guò)調(diào)用有道翻譯的api,實(shí)現(xiàn)中譯英、其他語(yǔ)言譯中文
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 # 應(yīng)用id self.appSecret = appSecret # 應(yīng)用密鑰 self.langFrom = 'auto' # 翻譯前文字語(yǔ)言,auto為自動(dòng)檢查 self.langTo = 'auto' # 翻譯后文字語(yǔ)言,auto為自動(dòng)檢查 def getUrlEncodedData(self, queryText): ''' 將數(shù)據(jù)url編碼 :param queryText: 待翻譯的文字 :return: 返回url編碼過(guò)的數(shù)據(jù) ''' salt = str(int(round(time.time() * 1000))) # 產(chǎn)生隨機(jī)數(shù) ,其實(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請(qǐng)求,不是請(qǐng)求 data = urllib.urlencode(payload) return data def parseHtml(self, html): ''' 解析頁(yè)面,輸出翻譯結(jié)果 :param html: 翻譯返回的頁(yè)面內(nèi)容 :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 '有道詞典結(jié)果' print youdaoResult print '-' * 10 def translate(self, queryText): data = self.getUrlEncodedData(queryText) # 獲取url編碼過(guò)的數(shù)據(jù) target_url = self.url + '?' + data # 構(gòu)造目標(biāo)url request = urllib2.Request(target_url, headers=self.headers) # 構(gòu)造請(qǐng)求 response = urllib2.urlopen(request) # 發(fā)送請(qǐng)求 self.parseHtml(response.read()) # 解析,顯示翻譯結(jié)果 if __name__ == "__main__": appKey = '應(yīng)用id' # 應(yīng)用id appSecret = '應(yīng)用密鑰' # 應(yīng)用密鑰 fanyi = YouDaoFanyi(appKey, appSecret) while True: queryText = raw_input("請(qǐng)輸入你好翻譯的文字[Q|quit退出]: ").strip() if queryText in ['Q', 'quit']: break fanyi.translate(queryText)