Match 2 words in a line of file

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Jan 19 03:15:54 CET 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