-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathir_engine.py
164 lines (136 loc) · 5.49 KB
/
ir_engine.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
"""\
------------------------------------------------------------
USE: python <PROGNAME> (options)
OPTIONS:
-h : print this help message
-s : use "with stoplist" configuration (default: without)
-p : use "with stemming" configuration (default: without)
-w LABEL : use weighting scheme "LABEL" (LABEL in {binary, tf, tfidf}, default: binary)
-o FILE : output results to file FILE
------------------------------------------------------------\
"""
#==============================================================================
# Importing
import sys, getopt, re
from my_retriever import Retrieve
#==============================================================================
# Command line processing
class CommandLine:
def __init__(self):
opts, args = getopt.getopt(sys.argv[1:], 'hspw:o:')
opts = dict(opts)
self.exit = True
if '-h' in opts:
self.printHelp()
return
if len(args) > 0:
print("*** ERROR: no arg files - only options! ***", file=sys.stderr)
self.printHelp()
return
if '-w' in opts:
if opts['-w'] in ('binary', 'tf', 'tfidf'):
self.termWeighting = opts['-w']
else:
warning = (
"*** ERROR: term weighting label (opt: -w LABEL)! ***\n"
" -- value (%s) not recognised!\n"
" -- must be one of: binary / tf / tfidf"
) % (opts['-w'])
print(warning, file=sys.stderr)
self.printHelp()
return
else:
self.termWeighting = 'binary'
if '-o' in opts:
self.outfile = opts['-o']
else:
print("*** ERROR: must specify output file (opt: -o FILE) ***",
file=sys.stderr)
self.printHelp()
return
if '-s' in opts and '-p' in opts:
self.indexFile = 'index_withstoplist_withstemming.txt'
self.queriesFile = 'queries_withstoplist_withstemming.txt'
elif '-s' in opts:
self.indexFile = 'index_withstoplist_nostemming.txt'
self.queriesFile = 'queries_withstoplist_nostemming.txt'
elif '-p' in opts:
self.indexFile = 'index_nostoplist_withstemming.txt'
self.queriesFile = 'queries_nostoplist_withstemming.txt'
else:
self.indexFile = 'index_nostoplist_nostemming.txt'
self.queriesFile = 'queries_nostoplist_nostemming.txt'
self.exit = False
def printHelp(self):
progname = sys.argv[0]
progname = progname.split('/')[-1] # strip off extended path
help = __doc__.replace('<PROGNAME>', progname, 1)
print(help, file=sys.stderr)
#==============================================================================
# Load (precomputed) Index File for (preprocessed) Document Collection
class IndexLoader:
def __init__(self, indexFile):
self.index = {}
docidCountRE = re.compile('(\d+):(\d+)')
f = open(indexFile, 'r')
for line in f:
term = line.split(' ', 1)[0]
self.index[term] = {}
for (docid, count) in docidCountRE.findall(line):
docid = int(docid)
self.index[term][docid] = int(count)
def getIndex(self):
return self.index
#==============================================================================
# Load (preprocessed) Collection of Queries
class Queries:
def __init__(self, queriesFile):
self.qStore = {}
termCountRE = re.compile('(\w+):(\d+)')
f = open(queriesFile, 'r')
for line in f:
qid = int(line.split(' ', 1)[0])
self.qStore[qid] = {}
for (term, count) in termCountRE.findall(line):
self.qStore[qid][term] = int(count)
def getQuery(self, qid):
if qid in self.qStore:
return self.qStore[qid]
else:
print("*** ERROR: unknown query identifier (\"%s\") ***" % qid, file=sys.stderr)
if type(qid) == type(''):
print('WARNING: query identifiers should be of type: integer', file=sys.stderr)
print(' -- your query identifier is of type: string', file=sys.stderr)
print(' -- program exiting', file=sys.stderr)
def qids(self):
return sorted(self.qStore)
#==============================================================================
# Store for Retrieval Results
class ResultStore:
def __init__(self, outfile):
self.outfile = outfile
self.results = []
def store(self, qid, docids):
if len(docids) > 10:
docids = docids[:10]
self.results.append((qid, docids))
def output(self):
with open(self.outfile, 'w') as out:
for (qid, docids) in self.results:
for docid in docids:
print(qid, docid, file=out)
#==============================================================================
# MAIN
if __name__ == '__main__':
config = CommandLine()
if config.exit:
sys.exit(0)
index = IndexLoader(config.indexFile).getIndex()
retrieve = Retrieve(index, config.termWeighting)
queries = Queries(config.queriesFile)
allResults = ResultStore(config.outfile)
for qid in queries.qids():
query = queries.getQuery(qid)
results = retrieve.forQuery(query)
allResults.store(qid, results)
allResults.output()