ubuntu下python脚本调用有道词典API实现命令行查词
#!/usr/bin/env python#coding=utf-8
'''
python使用有道词典的API来实现命令行查词
'''
import urllib2
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
key = '1096888977'
keyfrom = 'bloketest'
doctype = 'json'
u = 'http://fanyi.youdao.com/openapi.do'
class req:
def __init__(self):
self.key = key
self.keyfrom = keyfrom
self.doctype = doctype
def dict(self, words):
url = '%s?keyfrom=%s&key=%s&type=data&doctype=%s&version=1.1&q=%s' \
% (u, self.keyfrom, self.key, self.doctype, words)
solution_json = urllib2.urlopen(url).read()
solution_final = json.loads(solution_json)
try:
solutions = solution_final['translation']
print "[ \033"
for item in solutions: print '' + item
except KeyError:
print "无解..."
#扩展释义
try:
solutions = solution_final['basic']['explains']
print "[ \033"
for item in solutions: print '' + item
except:
pass
#网络释义
try:
solutions = solution_final['web']
print "[ \033"
for item in solutions.iteritems():
print '' + item
except KeyError, e:
pass
if __name__ == '__main__':
while 1:
try:
words = raw_input(u'\033[1;36;10m问:\033[0m ').strip()
except EOFError, e:
print "\nExit !"
break
except KeyboardInterrupt, e:
print "\nExit !"
break
if len(words) == 0: continue
if words == 'quit': break
req().dict(words)
页:
[1]