Match 2 words in a line of file

Rickard Lindberg ricli576 at student.liu.se
Thu Jan 18 19:23:43 EST 2007


elrondrules at gmail.com wrote:
> Hi
>
> Am pretty new to python and hence this question..
>
> I have file with an output of a process. I need to search this file one
> line at a time and my pattern is that I am looking for the lines that
> has the word 'event' and the word 'new'.
>
> Note that i need lines that has both the words only and not either one
> of them..
>
> how do i write a regexp for this.. or better yet shd i even be using
> regexp or is there a better way to do this....
>
> thanks

Maybe something like this would do:

import re

def lines_with_words(file, word1, word2):
    """Print all lines in file that have both words in it."""
    for line in file:
        if re.search(r"\b" + word1 + r"\b", line) and \
           re.search(r"\b" + word2 + r"\b", line):
            print line

Just call the function with a file object and two strings that
represent the words that you want to find in each line.

To match a word in regex you write "\bWORD\b".

I don't know if there is a better way of doing this, but I believe that
this should at least work.




More information about the Python-list mailing list