ITeye博客

金山词霸命令行客户端

eidolon · 2010-04-20 10:44 · Linux · 编程语言 · Markdown

查单词时进了金山词霸网站,见有开放接口,且非常之简单,仅一个接口。便萌生了写一个命令行工具的想法,已经习惯了使用命令行。代码如下:(因排版的原因,对代码有些许改动,如需要直接下载文件为好。)


#! /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 
好质量 

评论(5)

  1. #5 楼 · eidolon · 2010-04-27 15:38

    梦幻之星 writes:

    iciba.iciba("help") 会TraceBack

    没错,是会报错,这个问题前几天已经给ICIBA的人发邮件了,不过还没得到回复。 原因是返回的XML中有特殊特殊字符未作转义。如,help的返回值是:

    
    <dict num="219" id="219" name="219">
    <key>help</key>
    <ps>help</ps>
    <pron>http://res.iciba.com/resource/amp3/6/5/657f8b8da628ef83cf69101b6817150a.mp3</pron>
    <pos>n.</pos>
    <acceptation>帮忙, 补救办法, 助手, 治疗, <美>佣工</acceptation>
    <pos>vt.</pos>
    <acceptation>帮助, 助长, 接济, 治疗, 款待</acceptation>
    <pos>vi.</pos>
    <acceptation>有用, 救 命, 招待</acceptation>
    <acceptation>[计] 显示命令格式的简短概述</acceptation>
    ...
    </dict>
    
    

    <美>,这里的<和>是要分别写成 < 和 >。

  2. #4 楼 · 梦幻之星 · 2010-04-27 14:32

    iciba.iciba("help") 会TraceBack

  3. #3 楼 · eidolon · 2010-04-22 21:41

    如果查的是词组、短语之类有空格分割的,可以加引号,如:

    iciba "commit in"


    1. He would not commit himself in any way . 他不愿以任何方式做出承诺。

    1. After shooting his wife, he commit suicide in the bedroom. 在开枪打死妻子后,他在卧室自杀。

    1. Suicide is a risk: 95 percent of those who commit suicide in jail or prison have a diagnosed mental disorder. 存在着自杀的危险:拘留所或监狱中自杀的人中有95%被诊断为精神不正常。

    1. Using COMMIT and ROLLBACK in a server component COMMIT and ROLLBACK commands embedded in a server component may have different effects depending on the setting of the UseContextObject DBParm parameter. 那么插入的数据存在哪里?如果说新记录存在于数据库中,这和存在于硬盘中有什么区别??

    1. Did not Achan the son of Zerah commit a trespass in the matter of the devoted thing? 20从前谢拉的曾孙亚干,岂不是在那当灭的物上犯了罪么?
  4. #2 楼 · eidolon · 2010-04-21 11:48

    原来的代码有Bug,当 content 有特殊字符,如大于号、小于号等时会报错。双引号我已经做过处理,不过一直觉得处理方式太不合理了,有点头痛医头,脚痛看脚的感觉。所以又看了看代码,重构了一下。

  5. #1 楼 · 23号 · 2010-04-20 22:39

    coding=utf-8

    def characters(self, ch):
        ch = ch.encode('utf-8')
    

    utf8版本,谢谢。

评论功能维护中,当前仅展示历史评论。