-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocument_search.py
58 lines (44 loc) · 1.63 KB
/
document_search.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
#! /usr/bin/env python
import argparse
kPow = 2
def isEndDelimeter(c):
return c == '.' or c == '?' or c == '!' or c == ':'
def main(filepath, s):
with open(filepath, 'r') as fd:
t = fd.read()
t = t.replace('\n', ' ')
if len(t) < len(s):
return
s = s.lower()
len_s = len(s)
#Compute hash of search string and beginning window of text
lastEndIndex = -1
h_s = 0
h_t = 0
for i in range(len_s):
h_s *= kPow
h_s += ord(s[i].lower())
h_t *= kPow
h_t += ord(t[i].lower())
#Case we have a match right in the first window, now we perform a str cmp
found = h_s == h_t and s == t[i - len_s + 1 : i + 1].lower()
for i in range(len_s, len(t)):
#Update rolling hash in window
h_t -= (ord(t[i - len_s].lower())) * kPow**(len_s - 1)
h_t *= kPow
h_t += ord(t[i].lower())
#Case we have a match in the current window, now we perform a str cmp
if h_s == h_t and s == t[i - len_s + 1 : i + 1].lower():
found = True
#Found end of a sentence, so print out if we found a match anywhere within
if isEndDelimeter(t[i]):
if found:
print '* ' + t[lastEndIndex + 1 : i + 1].strip()
found = False
lastEndIndex = i
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Search a document for text.')
parser.add_argument('filepath', help='Path to the document to search in.')
parser.add_argument('word', help='Word to search for in document')
args = parser.parse_args()
main(args.filepath, args.word)