python3调用有道API

先在有道智云(http://ai.youdao.com/)申请账号

创建应用

python3调用有道API_第1张图片

创建实例

在创建的应用中绑定实例

python3调用有道API_第2张图片

查询appKey和secretKey,填入代码中

python3调用有道API_第3张图片

#/usr/bin/env python
#coding=utf8
import urllib.parse
import http.client
import random
import hashlib

appKey = '093265eac11c375b'
secretKey = 'OC4Yy0dfOxEyeClZuYVFg9l3WDRojQWk'

def youdaoTranslate(q):
    httpClient = None
    myurl = '/api'
    fromLang = 'EN'
    toLang = 'zh-CHS'
    salt = random.randint(1, 65536)
    sign = appKey+q+str(salt)+secretKey
    m1 = hashlib.new('md5')
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()
    myurl = myurl+'?appKey='+appKey+'&q='+ urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    try:
        httpClient = http.client.HTTPConnection('openapi.youdao.com')
        httpClient.request('GET', myurl)
        #response是HTTPResponse对象
        response = httpClient.getresponse()
        s = eval(response.read().decode("utf-8"))['translation']
        print(s)
    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()
    return s

if __name__ == '__main__':
    ss = youdaoTranslate('hello')
    print(ss)

你可能感兴趣的:(Python)