调用有道翻译API

时间:2023-12-20 13:55:20

前两天朋友说起NASA开放了数据API,今儿突然想起从来没用过外部提供的API,然而简单用得多的貌似是有道词典API,就像试试,本来觉得应该挺简单的,用urllib模块很快就实现了。

不过测试时才发现中文传递出现了问题:

先来看看在http://fanyi.youdao.com/openapi?path=data-mode申请Key与Keyfrom

网页下方有使用说明:

调用有道翻译API

其中<>内的就是你自己填的,在此doctype用json

调用有道翻译API

由此可以看出调用返回的“translation”就可以得到翻译后的值

代码如下:

 #coding:UTF-8
import urllib2
import json
from urllib import urlencode
from urllib import quote class Youdao:
def __init__(self):
self.url = 'http://fanyi.youdao.com/openapi.do'
self.key = '' #有道API key
self.keyfrom = 'pdblog' #有道keyfrom def get_translation(self,words):
url = self.url + '?keyfrom=' + self.keyfrom + '&key='+self.key + '&type=data&doctype=json&version=1.1&q=' + words
result = urllib2.urlopen(url).read()
json_result = json.loads(result)
json_result = json_result["translation"]
for i in json_result:
print i youdao = Youdao()
while True:
msg = raw_input()
msg = quote(msg.decode('gbk').encode('utf-8')) #先把string转化为unicode对象,再编码为utf-8.若没有此行则传入的中文没法翻译,英文可以!!!
youdao.get_translation(msg)

坑:urlencode只能够对字典型的键值对的数据格式起作用,故在此地不能够使用

  而看别人博客写到用urllib.quote方法可以将单个的string进行urlencode

    如果直接这样做的话仍然会报错:No JSON object could be decoded

  故实际应该先解码汉字的GBK编码在加码成为通用的utf-8编码后再quote即可。

调用有道翻译API

相关推荐博客:

http://www.pythonfan.org/thread-1173-1-1.html

http://www.cnblogs.com/ymy124/archive/2012/06/23/2559282.html

http://blog.chinaunix.net/uid-25063573-id-3033365.html