【转】网络翻译实现
上一篇 /
下一篇 2012-08-31 16:01:31
/ 个人分类:Python
原理:利用有道翻译api,提交要查询的单词,返回json结果,然后对结果进行解析输出。
代码在Win7中文系统,Py2.7.3调试通过,有道翻译的key要自己申请:
# -*- coding: cp936 -*-
import urllib
import json
kf = 'xxxx'
#申请的keyfromk = 'xxxxxxxxxx'
#申请的API keydef 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:
kf = 'xxx'
k = 'xxxx'
word = raw_input('输入英语单词: ')
if word == '':
continue
word = urllib.quote(word)
print word
url = 'http://fanyi.youdao.com/openapi.do?keyfrom='+ kf +'&key=' + k + '&type=data&doctype=json&version=1.1&q='+word
ret = urllib.urlopen(url).read()
dealjson(ret)
转载自:http://www.cnblogs.com/ma6174/
收藏
举报
TAG: