溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python通過調(diào)用有道翻譯api實現(xiàn)翻譯功能示例

發(fā)布時間:2020-10-05 21:48:07 來源:腳本之家 閱讀:293 作者:wanlifeipeng 欄目:開發(fā)技術(shù)

本文實例講述了Python通過調(diào)用有道翻譯api實現(xiàn)翻譯功能。分享給大家供大家參考,具體如下:

通過調(diào)用有道翻譯的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 # 應(yīng)用id
  self.appSecret = appSecret # 應(yīng)用密鑰
  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):
  '''
  解析頁面,輸出翻譯結(jié)果
  :param html: 翻譯返回的頁面內(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編碼過的數(shù)據(jù)
  target_url = self.url + '?' + data # 構(gòu)造目標(biāo)url
  request = urllib2.Request(target_url, headers=self.headers) # 構(gòu)造請求
  response = urllib2.urlopen(request) # 發(fā)送請求
  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|quit退出]: ").strip()
  if queryText in ['Q', 'quit']:
   break
  fanyi.translate(queryText)

關(guān)于有道翻譯api的詳細(xì)說明可參考其官網(wǎng):http://ai.youdao.com/docs/api.html

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python URL操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》

希望本文所述對大家Python程序設(shè)計有所幫助。

向AI問一下細(xì)節(jié)

免責(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)容。

AI