码迷,mamicode.com
首页 > 编程语言 > 详细

ubuntu下python脚本调用有道词典API实现命令行查词

时间:2016-07-07 22:45:16      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:命令行查词

#!/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[1;32;10m答\033[0m ]"
                        for item in solutions: print ‘  ‘ + item
                except KeyError:
                        print "无解..."
                #扩展释义
                try:
                        solutions = solution_final[‘basic‘][‘explains‘]
                        print "[ \033[1;32;10m扩展\033[0m ]"
                        for item in solutions: print ‘  ‘ + item
                except:
                        pass
                #网络释义
                try:
                        solutions = solution_final[‘web‘]
                        print "[ \033[1;32;10m网络\033[0m ]"
                        for item in solutions[0].iteritems():
                                print ‘  ‘ + item[1][0]
                        print
                except KeyError, e:
                        print
                        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)


ubuntu下python脚本调用有道词典API实现命令行查词

标签:命令行查词

原文地址:http://blokedream.blog.51cto.com/11607453/1812417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!