Question

I have this basic program. It takes a list of keywords, looks for those keywords in a string and if it finds a keyword, it does something based on that match.

I always forget the needed steps to print out the actual matching word from the string. I have a feeling I'm missing a for loop somewhere...

keywords = ["thing1","thing2"]


user_input = "This is a test to see if I can find thing2."

if any(word in user_input for word in keywords):

    print "keyword found", word #this gives me a -'word' not defined error"-

else:
    print "no"

Most straightforward way to do this?

Thanks! (and sorry for the really basic question, its just one of those things I forget a lot).

Was it helpful?

Solution

Regular Expressions will help:

import re    

words_list = [word for word in keywords if re.search(word, user_input )]
print "These words have been found: %s" % str(words_list)

OTHER TIPS

You could use a for-loop with an else clause:

for word in keywords:
    if word in user_input:
        print "keyword found", word 
        break
else:
    print "no"

Another way would be to use a generator expression and next to pull out the first item (if it exists):

try:
    word = next(word for word in keywords if word in user_input)
    print "keyword found", word
except StopIteration:
    print "no"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top