[Tutor] searching out keywords...

Sean 'Shaleh' Perry shalehperry@attbi.com
Fri, 08 Mar 2002 09:07:45 -0800 (PST)


On 08-Mar-2002 Bob X wrote:
> I have to monitor some hefty (min 40MB) log files. I have a list of keywords
> that I want to search for and then write those lines out to a different file.
> Basically I want to do this.
> 
> 1. run the py file with the log file as an ARG on the command line.
> 2. have it search that file for keywords
> 3. insert the lines that the keywords appears on into a different file
> 
>>> import string
>>> def contains_word(line, word):
...   return (string.find(line, word) != -1)
>>> contains_word('Sean "Shaleh" Perry', 'Perry')
1
>>> contains_word('Sean "Shaleh" Perry', 'Mom')

Then the question becomes whether or not partial matches are ok.

"This line of text has bluetooth connectivity" and we search for blue which
matches.  If this is not what you want then changing the string.find() to a
regex may work better.  re.search(r'\b%s\b' % word, line) seems like a good
start.  string.find () is likely faster though.

for word in words:
  if contains_word(line, word):
    print line
    break