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
         if "word2" in line:                          #works
         if "word3 word4 word5" in line:            #doesn't work

thanks in advance.
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
Due to the reasons discussed here we will be moving to on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
Posts: 1672
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.
Posts: 203
Joined: Tue Jun 04, 2013 7:53 pm

Re: match multiple words

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

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

Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 7 guests