先在有道智云(http://ai.youdao.com/)申请账号
创建应用
创建实例
在创建的应用中绑定实例
查询appKey和secretKey,填入代码中
#/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)