Python Searching For Exact Word/phrase Within A Text File
Currently, I'm trying to search for an exact word/phrase in a text file. I am using Python 3.4 Here is the code I have so far. import re def main(): fileName = input('Please i
Solution 1:
edit: Considering that you don't want to match partial words ('foo' should not match 'foobar'), you need to look ahead in the data stream. The code for that is a bit awkward, so I think regex (your current regex_search with a fix) is the way to go:
def regex_search(filename, term):
searcher = re.compile(term + r'([^\w-]|$)').search
with open(file, 'r') as source, open("new.txt", 'w') as destination:
for line in source:
if searcher(line):
destination.write(line)
Post a Comment for "Python Searching For Exact Word/phrase Within A Text File"