-
Notifications
You must be signed in to change notification settings - Fork 2
/
searchWord.py
executable file
·80 lines (65 loc) · 2.28 KB
/
searchWord.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
#!/usr/bin/python
import argparse
import re
''' A utility to search for a word in a text file. If found, returns the
complete paragraph the word was found in.
Useful in conjunction with gpg to use as a command line password manager
using a simple text file.
'''
def filesearch(pattern):
'''
Search each line of the file and return a list of line numbers
that match the pattern. There could be multiple returns.
'''
linecount = 0
founditems = []
for line in lines:
line = line.strip()
if p.search(line):
founditems.append(linecount)
linecount = linecount + 1
return founditems
def findstartpositions(founditems):
'''
Determine start positions by taking line number (item), subtract 1 and test
for a blank line.
'''
startpositions = []
for item in founditems:
while lines[item] not in ['\n', '\r\n']:
item = item - 1
startpositions.append(item + 1)
return startpositions
def makeunique(seq):
'''
Sometimes the search word is repeated within the paragraph, so make the
paragraphs that we print unique.
'''
return set(seq)
def printparagraph(startpositions):
'''
Print starting with startposition (a line number) and continue
until a blank line is encountered. If EOF is encountered, break.
'''
for start in startpositions:
while lines[start] not in ['\n', '\r\n']:
print(lines[start].strip())
start = start + 1
if lines[start] == lines[-1]:
break
print('\n')
return
parser = argparse.ArgumentParser(description="search for a word and display the surrounding paragraph")
parser.add_argument("pattern", help="the word you wish to match")
parser.add_argument("--input", type = argparse.FileType("r"), default = "-",
dest = "infile", help = "the file you wish to search,\
defaults to stdin")
args = parser.parse_args()
''' Read each line of the file into a list '''
lines = args.infile.readlines()
''' Compile a regular expression search pattern, case insensitive '''
p = re.compile(args.pattern, re.I | re.M)
founditems = filesearch(p)
startpositions = findstartpositions(founditems)
printparagraph(makeunique(startpositions))
args.infile.close()