調用有道翻譯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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM