调用有道翻译API

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

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

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

网页下方有使用说明:

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

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

代码如下:

 1 #coding:UTF-8
 2 import urllib2
 3 import json
 4 from urllib import urlencode
 5 from urllib import quote
 6 
 7 
 8 class Youdao:
 9     def __init__(self):
10         self.url = 'http://fanyi.youdao.com/openapi.do'
11         self.key = '993123434'  #有道API key
12         self.keyfrom = 'pdblog' #有道keyfrom
13 
14     def get_translation(self,words):
15         url = self.url + '?keyfrom=' + self.keyfrom + '&key='+self.key + '&type=data&doctype=json&version=1.1&q=' + words
16         result = urllib2.urlopen(url).read()
17         json_result = json.loads(result)
18         json_result = json_result["translation"]
19         for i in json_result:
20             print i
21 
22 
23 
24 youdao = Youdao()
25 while True:
26     msg = raw_input()
27     msg = quote(msg.decode('gbk').encode('utf-8'))             #先把string转化为unicode对象,再编码为utf-8.若没有此行则传入的中文没法翻译,英文可以!!!
28     youdao.get_translation(msg)

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

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

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

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

相关推荐博客:

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

原文地址:https://www.cnblogs.com/pengsixiong/p/4932601.html