查单词时进了金山词霸网站,见有开放接口,且非常之简单,仅一个接口。便萌生了写一个命令行工具的想法,已经习惯了使用命令行。代码如下:(因排版的原因,对代码有些许改动,如需要直接下载文件为好。)
可以将 iciba.py 拷贝到 /usr/bin 目录,这样就可以在任意目录使用了。还可以将名字改成 iciba,使用时就可以少打几个字符了:D
第一次写 Python 代码,有此零乱,诸位见谅。
#! /usr/bin/python
# coding=GBK
#
# CLI client for iciba.com
#
# FileName: iciba.py
__author__="eidolon"
__date__ ="$2010-4-19 18:25:36$"
import getopt
import sys
import urllib
import xml.sax
from xml.sax.handler import ContentHandler
from getopt import GetoptError
ICIBA_URL = "http://dict-co.iciba.com/api/dictionary.php?"
SEPARATE_LINE = '--------------------------------------------------------'
class ICIBAResponseHandler(ContentHandler):
"""The ICIBA response xml handler.
"""
def __init__(self, pron):
self.enter_node = 0
self.current_node = ''
self.sentence_counter = 0
self.pron = pron
def startElement(self, name, attrs):
self.current_node = name
if name in ('key', 'ps', 'pos', 'acceptation', 'orig', 'trans', 'pron'):
self.enter_node = 1
else:
self.enter_node = 0
if name in ('orig'):
self.sentence_counter += 1
print str(self.sentence_counter) + '.',
if name in ('acceptation'):
print '',
if name in ('ps'):
print '(',
if name in ('sent'):
print SEPARATE_LINE
def endElement(self, name):
if name in ('acceptation', 'orig', 'trans'):
print ''
if name in ('ps'):
print ')'
print SEPARATE_LINE
def characters(self, ch):
if self.enter_node:
if self.current_node in ('key', 'ps', 'pos', 'acceptation', 'orig', 'trans'):
print ch,
elif self.current_node == 'pron' and self.pron:
print 'Pron. URL: ' + ch
def iciba(word, pron=False):
response = urllib.urlopen(ICIBA_URL + urllib.urlencode({'w': word}, 'true'))
xml.sax.parse(response, ICIBAResponseHandler(pron))
response.close()
def usage():
print """USAGE: iciba.py [OPTIONS] <word1>[ <word2> ...]
OPTIONS
-p --with-pron, print prononce
"""
if __name__ == "__main__":
with_pron = False
try:
opts, args = getopt.getopt(sys.argv[1:], 'p', ['with-pron'])
except GetoptError:
usage()
sys.exit(1)
if ('-p', '') in opts: with_pron = True
if ('--with-pron', '') in opts: with_pron = True
if not args:
usage()
sys.exit(1)
else:
index = 1
for tmp in args:
iciba(tmp, with_pron)
if index < len(args):
index += 1
print '\n\n'
sys.exit(0)
可以将 iciba.py 拷贝到 /usr/bin 目录,这样就可以在任意目录使用了。还可以将名字改成 iciba,使用时就可以少打几个字符了:D
第一次写 Python 代码,有此零乱,诸位见谅。
# iciba good
good ( ɡʊd )
--------------------------------------------------------
n. 好, 好事, 慷慨的行为, 好处, 利益
adj. 优良的, 上等的, 虔诚的, 愉快的, 慈善的, 好心的, 有益的
--------------------------------------------------------
1. Good.
好。
--------------------------------------------------------
2. Good girl.
好孩子。
--------------------------------------------------------
3. especially good
尤佳
--------------------------------------------------------
4. " Good Lord! "
" 老天爷! "
--------------------------------------------------------
5. Good quality
好质量