-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.py
47 lines (36 loc) · 997 Bytes
/
index.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
import sys
from search.search import kmp_search
def print_result(matches):
output_str = ""
matches_num = 0
for line_matches in matches:
matches_num += len(line_matches[1])
line_res = "%11d |" % line_matches[0]
for position in line_matches[1]:
line_res += " %d" % position
output_str += line_res + "\n"
if matches_num:
print("Line number | Positions")
print("-----------------------")
print(output_str)
print("\nTotal matches: " + str(matches_num) + "\n")
argv = sys.argv
help_text = """
Usage:
python index.py file.txt | 'string to match' 'pattern'
"""
if len(argv) != 3:
print("Incorrect number of arguments provided\n" + help_text)
sys.exit(0)
match_target = argv[1]
pattern = argv[2]
try:
if '.txt' in match_target:
result = kmp_search(open(match_target, 'r').read(), pattern)
print_result(result)
else:
result = kmp_search(match_target, pattern)
print_result(result)
except Exception as e:
print(e)
sys.exit(0)