需要申请有道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)