match multiple words

This is the place for queries that don't fit in any of the other categories.

match multiple words

Postby eedodge3 » Tue Jul 30, 2013 5:37 pm

what's the simplest way to match multiple words with a line of a file opened for reading?

i'm looking something similar to this awk line. if means if a line contains all words between the slash, print something.
{if ($0 ~ /word1 word2 word3/ ) print $1$3}

this is what i have so far:
Code: Select all
with open(myfile,'r') as f:       
     for line in f:
         if "word1" in line:                          #works
             do.stuff()
         if "word2" in line:                          #works
             do.stuff()
         if "word3 word4 word5" in line:            #doesn't work
             do.stuff()


thanks in advance.
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm

Re: match multiple words

Postby Yoriz » Tue Jul 30, 2013 6:16 pm

Not tested
Code: Select all
if all(word in line for word in("word3", "word4", "word5")):
Last edited by Yoriz on Tue Jul 30, 2013 6:44 pm, edited 1 time in total.
Reason: noticed you want them all to be found so changed any to all
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 789
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: match multiple words

Postby ochichinyezaboombwa » Tue Jul 30, 2013 6:34 pm

One way to do that would be put your words in a list and loop through it:
Code: Select all
words = ["apple", "banana", "avocado"]
for i, ln in enumerate(open(flnm)):
    if all(word in ln for word in words):
        print "Found all in line %d" % (i), ln,


Note that it's not clear from your post whether you're looking for presence of words or substrings. e.g. "apple" is a sub-string of "I like pineapples" but this line doesn't have a word "apple". It's also not quite clear whether you want all words or any.
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: match multiple words

Postby eedodge3 » Tue Jul 30, 2013 8:48 pm

thanks Yoriz & ochichinyezaboombwa.
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 3 guests