forked from chenkaie/Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathydict-py
executable file
·296 lines (268 loc) · 7.55 KB
/
ydict-py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python
# coding=UTF-8
# Chen Wen <[email protected]>
# Web Site http://code.google.com/p/ydict/
# Blog : http://chenpc.csie.in
import httplib, urllib,string,sys
from HTMLParser import HTMLParser
from optparse import OptionParser
import locale
from codecs import EncodedFile
import shelve,os
import random
version="ydict 1.0.9"
red="\33[31;1m"
lindigo="\33[36;1m"
indigo="\33[36m"
green="\33[32m"
yellow="\33[33;1m"
blue="\33[34;1m"
org="\33[0m"
light="\33[0;1m"
learn=0
if os.access(os.getenv("HOME")+"/.ydict.db", os.F_OK):
db=shelve.open(os.getenv("HOME")+"/.ydict.db","c")
learn=1
def importfile(file):
fp = open(file)
db=shelve.open(os.getenv("HOME")+"/.ydict.db","c")
for line in fp:
newword=line.split(" ")[0]
if db.has_key(newword) == 0:
db[newword]=0
print "File imported!"
def result(count, total):
if total == 0:
print ""
exit()
print "\nScore: ",int(count),"/",int(total),"(",count/total,")"
exit()
def seckey(x):
return x[1]
def wordlearn():
wordlist = list(db.iteritems())
wordlist.sort(key=seckey)
size=len(wordlist)
totalcount = 0.0
right = 0.0
if size <= 1:
print "There must be at least two words needed in the list."
exit()
while True:
k=wordlist[int(random.triangular(0, size-1, 0))][0]
k=k.lower()
print dict(k,1).replace(k, "####").replace(k.upper(), "####").replace(k[0].swapcase()+k[1:].lower(),"####")
try:
word=raw_input("Input :")
except KeyboardInterrupt:
result(right,totalcount)
if word == k.lower():
print "Bingo!"
right+=1
db[k]+=1
if db[k] >= 100:
db[k]=100
else:
db[k]-=3
if db[k] < 0:
db[k]=0
print "WRONG! Correct answer is : ",k
try:
raw_input("Press Enter to contiune......")
except KeyboardInterrupt:
result(right,totalcount)
db.sync()
totalcount+=1
if totalcount % (int(size/4)+1) == 0:
wordlist=list(db.iteritems())
wordlist.sort(key=seckey)
def wordlist():
db=shelve.open(os.getenv("HOME")+"/.ydict.db","c")
wordlist = list(db.iteritems())
wordlist.sort(key=seckey)
for k,v in wordlist:
print k,v
class MyHTMLParser(HTMLParser):
redirect=0
pron=True
def __init__(self):
self.show=0
self.prefix=""
self.postfix=org
self.entry=1
self.desc=0
self.result=[]
self.learn=learn
self.learnword=0
self.chinese=0
def handle_starttag(self, tag, attrs):
if self.redirect == 1 and tag == "strong":
self.show=1
self.prefix="Spell Check: ["+yellow
self.postfix=org+"]"
elif tag == "span" and len(attrs)==0:
if self.pron == True:
self.show=1
self.prefix=""
elif tag == "div" and len(attrs)==0:
if self.pron == True:
self.show=1
self.prefix=""
elif tag == "div" and len(attrs)!=0:
if attrs[0][1]=="pronunciation" and self.pron==True:
self.result.append(blue)
elif attrs[0][1]=="caption":
self.show=1
self.prefix=red
elif attrs[0][1]=="theme clr":
self.show=1
if self.chinese == 0:
self.learnword=1
self.prefix="["+light
self.postfix=org+"]"
elif attrs[0][1]=="description":
if self.desc != 0:
self.show=1
self.prefix=" "+org
self.desc+=1
elif tag == "p" and len(attrs)!=0:
if attrs[0][1] == "example":
self.show=1
self.prefix=" "+indigo
elif attrs[0][1] == "interpret":
self.show=1
self.prefix=" "+org+str(self.entry)+"."
self.entry+=1
def handle_data(self,data):
if self.show == 1:
self.result.append(self.prefix+data+self.postfix+"\n")
self.show=0
self.prefix=""
self.postfix=""
if(self.learn == 1 and self.learnword == 1):
if(db.has_key(data.lower()) == 0 and data.lower().isalpha() ):
db[data.lower()]=0
self.learnword=0
def handle_endtag(self, tag):
if tag == "div":
self.result.append(org)
def htmlspcahrs(content):
content=content.replace("&","&")
content=content.replace("'","\'")
content=content.replace(""","\"")
content=content.replace(">",">")
content=content.replace("<","<")
content=content.replace("<span>","")
content=content.replace("</span>","")
content=content.replace("<b>",lindigo)
content=content.replace("</b>",org+indigo)
content=content.replace("\n","\n "+green)
return content
def http_postconn(word):
yahoourl="tw.dictionary.yahoo.com"
params = urllib.urlencode({'p': word ,'ei' : 'UTF-8'})
return urllib.urlopen("http://%s/search" % yahoourl, params)
def dict(word,pron):
output=""
word=word.strip()
if len(word) <= 0:
return output
r1=http_postconn(word)
data1 = r1.read()
p=MyHTMLParser()
p.redirect=0
p.chinese=0
p.pron=pron
try:
#data1=data1[:16+string.index(data1,"Online Resources")]
data1=data1[:16+string.index(data1,'<div id="adbn_BE" class="ad">')]
except ValueError:
return output
try:
index1=string.index(data1,"您是不是要查")
p.redirect=1
except ValueError:
try:
index1=string.index(data1,"很抱歉,字典找不到您要的資料喔!")
return yellow+"Not Found!"+org+"\n"
except ValueError:
index1=string.index(data1,"字典搜尋")
try:
index3=string.index(data1,"以下為 <strong>")
index4=string.index(data1,"</strong> 在字典中的結果")
print yellow+"以下為 "+light+data1[index3+18:index4]+yellow+" 在字典中的結果"+org
except ValueError:
pass
try:
string.index(data1,"拼音")
string.index(data1,"注音")
p.chinese=1
except ValueError:
pass
data=data1[index1:]
p.reset()
data=htmlspcahrs(data)
p.feed(data)
for s in p.result:
output+=s
return output
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-s", "--step", dest="step", help="one step mode.",default=False,action="store_true")
parser.add_option("-p", "--pron", dest="pron", help="disable pronounce.",default=True,action="store_false")
parser.add_option("-u", "--utf8", dest="utf8", help="force utf-8 encoding.",default=False,action="store_true")
parser.add_option("-b", "--big5", dest="big5", help="force big5 encoding.",default=False,action="store_true")
parser.add_option("-w", "--word", dest="oneword", type="string" , help="only one word.",action="store")
parser.add_option("-v", "--version", dest="version", help="show version.",default=False,action="store_true")
parser.add_option("-d", "--database", dest="database", help="initial database.",default=False,action="store_true")
parser.add_option("-l", "--learn", dest="learnmode", help="start learning mode.",default=False,action="store_true")
parser.add_option("-a", "--list", dest="listall", help="list all word in list.",default=False,action="store_true")
parser.add_option("-i", "--import", dest="importfile", type="string", help="import a word list",default=False,action="store")
(options, args) = parser.parse_args()
m_pron=options.pron
(lang , enc)=locale.getdefaultlocale()
if options.importfile:
importfile(options.importfile)
exit()
if options.version == True:
print version
exit()
if options.utf8 == True:
enc="utf8"
elif options.big5 == True:
enc="big5"
if options.database == True:
db=shelve.open(os.getenv("HOME")+"/.ydict.db","c")
db.close()
exit()
if options.utf8 == options.big5 ==True:
print "Can not select utf-8 and big5 at the same time"
exit()
if enc == 'big5':
m_pron=False
if True:
result=dict(sys.argv[1],m_pron)
result=unicode(result,'utf8')
result=result.encode(enc)
print result
exit()
if options.learnmode:
wordlearn()
elif options.listall:
wordlist()
exit()
while(1):
try:
word=raw_input("<PyDict> ")
except KeyboardInterrupt:
print ""
exit()
except EOFError:
print ""
exit()
result=dict(word,m_pron)
result=unicode(result,'utf8')
result=result.encode(enc)
print result
if options.step == True:
exit()