-
Notifications
You must be signed in to change notification settings - Fork 1
/
searchdict.py
62 lines (43 loc) · 1.54 KB
/
searchdict.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import optparse
import re
import csv
import xml.etree.cElementTree as etree
import sys
reload(sys)
sys.setdefaultencoding("utf_8")
def searchdict(word,dict):
pattern=re.compile(u"\\b"+word+u"\\b",re.U | re.IGNORECASE)
hits=[]
index=0
for (lang1,lang2) in dict:
result1=pattern.search(lang1)
result2=pattern.search(lang2)
if result1 is not None or result2 is not None:
hits.append(index)
index += 1
for hit in hits:
print dict[hit][0]," <=> ", dict[hit][1]
def main():
parser = optparse.OptionParser()
parser.usage = """A program for searching words in a dictionary (CSV format) generated by generatedict.py ."""
parser.add_option("-i", "--in", dest="filein", help="dictionary file (CSV)", metavar="INFILE")
(options, args) = parser.parse_args()
if options.filein is None:
parser.error("Missing input file!")
try:
# "rb" : readable, binary file (just reading a stream of bytes, no decoding)
filein=open(options.filein, "rb")
dictReader=csv.reader(filein)
dictionary=[]
for row in dictReader:
dictionary.append((unicode(row[0]),unicode(row[1])))
word=raw_input("Enter word to translate: ")
searchdict(word,dictionary)
except IOError:
print "Cannot read from ", options.filein
if __name__ == "__main__":
# when one "executes" a python program, it's __name__ is
# __main__, otherwise it's name will be the module name
main()