Match 2 words in a line of file

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Jan 18 21:15:54 EST 2007


MrJean1 wrote:
> def lines_with_words(file, word1, word2):
>     """Print all lines in file that have both words in it."""
>     for line in file:
>         words = line.split()
>         if word1 in words and word2 in words:
>             print line

This sounds better, it's probably faster than the RE version, Python
2.5 has a really fast str.__contains__ method, done by effbot:

def lines_with_words(file, word1, word2):
    """Print all lines in file that have both words in it.
    (word1 may be the less frequent word of the two)."""
    for line in file:
        if word1 in line and word2 in line:
            print line

Bye,
bearophile




More information about the Python-list mailing list