本篇全文出自:胖貓Blog

 


最近在學習python,在 FourDollars的Blog上發現這篇Yahoo!奇摩字典 command line version。
後來在Tsung's Blog的文字介麵線上字典 Script上發現更多版本,有sh,perl,java,就是沒有python,所以就拿這個題目來練練手拉

在big5環境下執行的話請將iscp950=False改成iscp950=True
排版看起來很慘阿
不管了有空再來弄,有沒有人可以給些建議阿..

 


1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3 import sys
4 import getopt
5 import httplib
6 import re
7 iscp950=False
8 def inCP950(data):
9 if iscp950:
10 return data.decode('utf-8').encode('cp950')
11 else:
12 return data
13
14 def loopSearch():
15 while True:
16 print inCP950("<Yahoo Yahoo 奇摩字典>")
17 inargs=sys.stdin.readline()
18 Search(inargs)
19
20 def Search(word):
21 try:
22 conn = httplib.HTTPConnection('tw.dictionary.yahoo.com:80')
23 except h2.error,msgs:
24 print msgs
25 sys.exit(2)
26
27 conn.request("GET", "/search?p="+word)
28 r1 = conn.getresponse()
29 r1.status,r1.reason
30 data=r1.read()
31 dataline=data.splitlines()
32 for line in dataline:
33 prog = re.compile('<div class=pcixin>(.+)</div>')
34 result = prog.findall(line)
35 for pcixin in result:
36 if pcixin!=None:
37 print inCP950(pcixin)
38
39 prog = re.compile('<div class=pexplain>(.+)</div>')
40 result = prog.findall(line)
41 for pexplain in result:
42 if pexplain!=None:
43 print '\t',inCP950(pexplain)
44
45 prog = re.compile('<div class=peng><span id=dropdownid>(.+)</span></div>')
46 result = prog.findall(line)
47 for peng in result:
48 if peng != None:
49 print '\t\t',inCP950(peng)
50
51 prog = re.compile('<div class=pchi><span id=dropdownid>(.+)</span></div>')
52 result = prog.findall(line)
53 for pchi in result:
54 if pchi != None:
55 print '\t\t',inCP950(pchi)
56
57 if __name__ == "__main__":
58 loopSearch()
arrow
arrow
    全站熱搜

    正義的胖虎 發表在 痞客邦 留言(1) 人氣()