How do I check if a sentence contains a certain word in Python and then perform an action?

Going based on the comment by @knitti, the problem is that you need to split up the sentence into words first, then check:

term = "message" #term we want to search for
input = raw_input() #read input from user

words = input.split() #split the sentence into individual words

if term in words: #see if one of the words in the sentence is the word we want
    do_stuff()

Otherwise if you had the sentence "That one is a classic" and you tried to check if it contained the word "ass", it would return True incorrectly.

Of course, this still isn't perfect because then you might have to worry about things like stripping out punctuation and what not (like , . etc.) because otherwise the sentence "That one is a classic." would still return False for a search for "classic" (because of the period at the end). Rather than reinvent the wheel, here's a good post on stripping punctuation from a sentence in Python:

Best way to strip punctuation from a string in Python

There's case-sensitivity to consider too, so you might want to change the raw_input result and your search term to lowercase before doing a search. You could easily do that by just using the lower() function on the str class.

These problems always seem to simple...


This is of course a very simple example:

if "message" in raw_input():
    action()

If you are required to map different words to different actions, then you could do something like this:

# actions
def action():
    print "action"

def other_action():
    print "other action"

def default_action():
    print "default action"

# word to action translation function
def word_to_action(word):
    return {
        "message":  action,
        "sentence": other_action
    }.get(word, default_action)()

# get input, split into single words
w = raw_input("Input: ").split()

# apply the word to action translation to every word and act accordingly
map(word_to_action, w)

Note, that this also defines a default action for the case when the input does not contain any of the trigger words.

See here for more details on the above mapping idiom, which is actually Python's way of achieving 'switch statement'.

Tags:

Python

Input