-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_based_document_store.py
47 lines (34 loc) · 1.54 KB
/
file_based_document_store.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
from collections import defaultdict
class DocumentStore(object):
def parse_query(self, query_string):
query_tokens = query_string.split('-')
operator = query_tokens[0]
query_terms = query_tokens[1:]
return operator, query_terms
def fetch(self, id):
return self.documents[id]
class LinearFileBasedDocumentStore(DocumentStore):
def initialize(self, filename):
with open(filename) as f:
self.documents = f.read().splitlines()
def query(self, query_string):
operator, query_terms = self.parse_query(query_string)
predicate = any if operator == 'OR' else all
return [ id for id, document in enumerate(self.documents)
if predicate(term in document.lower() for term in query_terms)]
class IndexedFileBasedDocumentStore(DocumentStore):
def initialize(self, filename):
with open(filename) as f:
self.documents = f.read().splitlines()
self.index = self.build_index_from_documents()
def build_index_from_documents(self):
index = defaultdict(set)
for id, document in enumerate(self.documents):
for word in [w.lower() for w in document.split(' ')]:
index[word].add(id)
return index
def query(self, query_string):
operator, query_terms = self.parse_query(query_string)
predicate = set.union if operator == 'OR' else set.intersection
matches = [ self.index[term] for term in query_terms ]
return sorted(list(predicate(*matches)))