Python: common mistake while searching for a keyword in a set of files

Recently, I was developing a tool for my own use which could help me find a keyword in a heap of files based on the keyword importance,date modified and so on. I was developing this tool to increase my own productivity, so that I could find the keywords I need, and then deploy the files based on that on the server. Although I had done the program right, there was something missing in the way I searched for the strings.
for line in inp.readlines():
for word in line.split():
#print word
if regex.match(word):
print Keyword +word+ exists in : +f
#else:
#print No Match
inp.close()

Can you point out the mistake here? the mistake was that I was only matching the strings. Python offers two different primitive operations based on regular expressions: match and search. If you are accustomed to Perls semantics, the search operation is what youre looking for. See the search() function and corresponding method of compiled regular expression objects.

Note that match may differ from search using a regular expression beginning with ^: ^ matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The “match operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it.

for line in inp.readlines():
for word in line.split():
#print word
if regex.search(word):
print Keyword +word+ exists in : +f
#else:
#print No Match
inp.close()

The above code just works fine for searching keyword in a set of files. You can use os.walk to go through a directory structure.

In

Leave a Reply

Your email address will not be published. Required fields are marked *