python调用有道翻译api实现翻译

通过调用有道翻译的api,实现中译英、其他语言译中文

代码:

# 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):
        '''
        将数据url编码
        :param queryText: 待翻译的文字
        :return: 返回url编码过的数据
        '''
        salt = str(int(round(time.time() * 1000)))  # 产生随机数 ,其实固定值也可以,不如"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编码过的数据
        target_url = self.url + '?' + data    # 构造目标url
        request = urllib2.Request(target_url, headers=self.headers)  # 构造请求
        response = urllib2.urlopen(request)  # 发送请求
        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)

参考文档: http://ai.youdao.com/docs/api.s

转载于:https://www.cnblogs.com/hupeng1234/p/7073682.html

你可能感兴趣的:(python调用有道翻译api实现翻译)