python 有道翻译 api接口

最近有一个调用 "有道词典 api接口" 的需求,就有了如下的代码:

 

# -*-coding:utf-8 -*-
'''
@File       : youdao.py
@Author     : HW Shen
@Date       : 2019/8/5
@Desc       :
'''

import urllib.parse
import http.client
import random
import hashlib

# 通过在http://ai.youdao.com/ 执行以下操作获取
# 1.注册账号 => 2.创建应用 => 3.创建实例 => 4.应用绑定对象
appKey = '784ece665fa5e907'
secretKey = 'Ap2IyfAaaDUryMR4Q7l8u73ZGoC9vOSZ'


# 中译英
def Ch2En(item):
    httpClient = None
    myurl = '/api'

    fromLang = 'zh-CHS'  # 译文主体
    toLang = 'EN' # 译文客体

    salt = random.randint(1, 65536)
    sign = appKey + item + str(salt) + secretKey
    m1 = hashlib.new('md5')
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()
    
    # 拼接完整译文对象
    myurl = myurl + '?appKey=' + appKey + '&q=' + urllib.parse.quote(
        item) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign

    result = ""
    try:
        httpClient = http.client.HTTPConnection('openapi.youdao.com')
        httpClient.request('GET', myurl)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result = eval(response.read().decode("utf-8"))['translation']
        # print(type(result))
    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()
    return result


# 英译中
def En2Ch(item):
    httpClient = None
    myurl = '/api'

    fromLang = 'EN' # 译文主体
    toLang = 'zh-CHS' # 译文客体

    salt = random.randint(1, 65536)
    sign = appKey + item + str(salt) + secretKey
    m1 = hashlib.new('md5')
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()
    myurl = myurl + '?appKey=' + appKey + '&q=' + urllib.parse.quote(
        item) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign

    result = ""
    try:
        httpClient = http.client.HTTPConnection('openapi.youdao.com')
        httpClient.request('GET', myurl)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result = eval(response.read().decode("utf-8"))['translation']

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()
    return result


if __name__ == '__main__':
    c2e = Ch2En('假日')
    print("Ch2En:", c2e)
    e2c = En2Ch(c2e[0])
    print("En2Ch:", e2c)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值