網絡翻譯-利用有道接口

需要申請有道API的key

# -*- coding:UTF-8 -*-  

import urllib
import json
def dealjson(ret):
    ret = json.loads(ret)
    error = ret['errorCode']
    print error
    if error == 20:
        print '要翻譯的文本過長'
    elif error == 30:
        print '無法進行有效的翻譯'
    elif error == 40:
        print '不支持的語言類型'
    elif error == 50:
        print '無效的key'
    elif error == 0:
        trans = ret['translation']
        for i in trans:
            print i
        print ret['query']
        if 'basic' in ret.keys():
            explain =  ret['basic']['explains']
            for i in explain:
                print i
                web =ret['web']
                for i in web:
                    print i['key'],
                    for j in i['value']:
                        print j,
                    print 


if __name__=='__main__':
    while True:
        word = raw_input('input: ')
        if word == '':
            continue
        word = urllib.quote(word)
        print word
        url = 'http://fanyi.youdao.com/openapi.do?keyfrom={}&key={}&type=data&doctype=json&version=1.1&q='+word
        ret = urllib.urlopen(url).read()
        dealjson(ret) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章