@@ -147,15 +147,17 @@ def query(self, query_text, n=10):
147147 qwords = [w for w in words (query_text ) if w not in self .stopwords ]
148148 shortest = argmin (qwords , lambda w : len (self .index [w ]))
149149 docs = self .index [shortest ]
150- results = sorted ([(sum ([self .score (w , d ) for w in qwords ]), d ) for d in docs ])
151- results .reverse ()
152- return results [:n ]
150+ return heapq .nlargest (n , ((total_score (qwords , doc ), doc ) for doc in docs ))
153151
154- def score (self , word , docid ):
152+ def score (self , word , doc ):
155153 "Compute a score for this word on this docid."
156154 # There are many options; here we take a very simple approach
157- return (math .log (1 + self .index [word ][docid ]) /
158- math .log (1 + self .documents [docid ].nwords ))
155+ return (math .log (1 + self .index [word ][doc ]) /
156+ math .log (1 + self .documents [doc ].nwords ))
157+
158+ def total_score (qwords , doc ):
159+ "Compute the sum of the scores of the queried words on this doc."
160+ return sum (self .score (qword , doc ) for qword in qwords )
159161
160162 def present (self , results ):
161163 "Present the results as a list."
0 commit comments