-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTask1_TfIdf.py
252 lines (218 loc) · 6.97 KB
/
Task1_TfIdf.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
#!/usr/bin/env python
import os
import glob
import re
import math
import operator
from collections import *
import decimal
import time
from threading import Thread
decimal.getcontext().prec = 10
InputQueries = []
queryFile = os.getcwd() + '\\cacm.query'
uniGram_DfTable = open (os.getcwd() + '\\MyIndex\\OneGram_DfTable.txt', 'r').read()
uniGram_TfTable = open(os.getcwd() + '\\MyIndex\\OneGram_TfTable.txt', 'r').read()
PlainTextFolder = os.getcwd() + '\\PlainText'
IndexMappingDoc = open(os.getcwd() + '\\DocumentIndexMapping_CACM.txt', 'r').read()
N = 0
numericRegex = r'(\d{1,3},\d{3}(,\d{3})*)(\.\d*)?|\d+\.?\d*'
alphanumericRegex = '.*\\d+.*'
def corpusSize():
return (len(IndexMappingDoc.split('\n')) - 1)
def queries():
queries = open(queryFile, 'r').read()
pattern = re.compile(r'</DOCNO>(.*?)</DOC>')
lst = re.findall(pattern, queries.replace('\n',' '))
for query in lst:
InputQueries.append(removePunctuation(query.strip().lower()))
def splitQuery(query):
query.strip().split(' ')
def removePunctuation(text):
pattern = re.compile(numericRegex)
if hasNumber(text):
text = preservePunctuation(text)
else:
if ',' in text:
text = text.replace(',',' ')
if '.' in text:
text = text.replace('.',' ')
if '/' in text:
text = text.replace('/',' ')
if '?' in text:
text = text.replace('?',' ')
if '!' in text:
text = text.replace('!',' ')
if '"' in text:
text = text.replace('"',' ')
if '~' in text:
text = text.replace('~',' ')
if '@' in text:
text = text.replace('@',' ')
if '#' in text:
text = text.replace('#',' ')
if '(' in text:
text = text.replace('(',' ')
if ')' in text:
text = text.replace(')',' ')
if '^' in text:
text = text.replace('^',' ')
if '[' in text:
text = text.replace('[',' ')
if ']' in text:
text = text.replace(']',' ')
if ':' in text:
text = text.replace(':',' ')
if ';' in text:
text = text.replace(';',' ')
if '&' in text:
text = text.replace('&',' ')
if ' ' in text:
text = text.replace(' ',' ')
if text != '' and (text[-1] == '.' or text[-1] == ','):
return text[:-1]
return text
def hasNumber(text):
pattern = re.compile(alphanumericRegex)
if re.match(pattern, text):
return True
return False
def preservePunctuation(text):
n = len(text)
i = 0
while i < n-1:
if i>0 and (text[i] == ',' or text[i] == '.'):
if not (re.match('[0-9]', text[i - 1]) and re.match('[0-9]', text[i + 1])):
text = text[:i] + text[(i+1):]
n-=1
i+=1
return text
def getTermDocIds(term):
if '*' in term:
term = term.replace('*','\*')
if '+' in term:
term = term.replace('+','\+')
pattern = re.compile(r'\n' + term + ' (.+?) ')
result = re.findall(pattern, uniGram_DfTable)
doc = []
if len(result) > 0:
doc = result[0].split(',')
return doc
def getDoc(docId):
pattern = re.compile(r'\n' + docId + ', (.+?), ')
result = re.findall(pattern, IndexMappingDoc)
doc = ''
if len(result) > 0:
doc = result[0] + '.txt'
return doc
def getTextTif(text):
wordFreq = {}
for unigram in text.split(' '):
word = unigram.strip("'").strip()
if word == '':
continue
if word in wordFreq:
wordFreq[word] += 1
else:
wordFreq[word] = 1
return wordFreq
def getDocTif(doc):
text = open(PlainTextFolder + '\\' + doc).read()
return getTextTif(text)
def getTf(term, text):
if '*' in term:
term = term.replace('*','\*')
if '+' in term:
term = term.replace('+','\+')
pattern = re.compile(r' \b' + term + r'\b ')
return len(re.findall(pattern, text))
def getTermWeightInQuery(term, queryDict, query):
return decimal.Decimal(queryDict[term])/(getTextLength(query))
def getTermWeightInDoc(term, idf, tf, docLen):
termComp = float(tf)
numerator = decimal.Decimal((termComp)*idf)
return numerator
def getTextLength(text):
return len(text.split(' '))
def getIdf(n):
if n == 0:
return 0
return math.log(N/n, 10)
def getDocScore(query, docId):
queryDict = getTextTif(query)
numerator = decimal.Decimal(0.0)
wDocSqSum = decimal.Decimal(0.0)
wQuerySqSum = decimal.Decimal(0.0)
docText = open(PlainTextFolder + '\\' + (getDoc(docId))).read()
docLen = getTextLength(docText)
for term in queryDict:
tf = getTf(term, docText)
idf = getIdf(len(getTermDocIds(term)))
wQuery = getTermWeightInQuery(term, queryDict, query)
wDoc = getTermWeightInDoc(term, idf, tf, docLen)
numerator += wDoc*wQuery
return numerator
def getQueryDocs(query):
docs = []
queryTif = getTextTif(query)
for term in queryTif:
tD = getTermDocIds(term)
for docId in tD:
if docId not in docs:
docs.append(docId)
return docs
def scoreDocuments(query, batch):
global scoredDoc
for docId in batch:
scoredDoc[docId] = getDocScore(query, docId)
def multiThreadAssignment(query, queryDocs):
threads = []
threadCount = 16
docBatch = len(queryDocs)/threadCount
batchSet = 0
i=1
batches = 0
while batchSet < len(queryDocs) and i < threadCount:
batch = queryDocs[batchSet : batchSet + docBatch]
t = Thread(target=scoreDocuments, args=(query, batch, ))
t.start()
threads.append(t)
batches += len(batch)
batchSet += docBatch
i+=1
batch = queryDocs[batches:]
t = Thread(target=scoreDocuments, args=(query, batch, ))
t.start()
threads.append(t)
for t in threads:
t.join()
def assignScoresToDocs(query):
global scoredDoc
start = time.time()
scoredDoc = {}
queryDocs = getQueryDocs(query)
multiThreadAssignment(query, sorted(queryDocs))
end = time.time()
print 'Elapsed Time: %lf' % (end - start)
return (OrderedDict(sorted(scoredDoc.items(), key=lambda x: x[1], reverse = True)))
queries()
N = corpusSize()
print 'Total Documents - %d' % N
with open('TfIdf_QueryResults.txt','a+') as queryResults:
queryResults.write('query_id Q0 docid rank TfIdf_score system_name')
i = 1
j = 1
for query in InputQueries:
print 'query - %d' % i
print query
docs = assignScoresToDocs(query)
rank = 1
with open('TfIdf_Query_%d_Result.txt' % i,'a+') as queryResult:
queryResult.write('query_id Q0 docid rank TfIdf_score system_name')
for doc in docs:
queryResults.write('\n%d Q0 %s %d %lf TfIdf' % (i, doc, rank, docs[doc]))
queryResult.write('\n%d Q0 %s %d %lf TfIdf' % (i, doc, rank, docs[doc]))
if rank == 100:
break
rank += 1
i+=1