Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

input

Let's say that I ask a user for raw input and they said, "This is a message." If that raw input contained the word "message" it would perform an action after that. Could I see how this can be done?

like image 279
Noah R Avatar asked Oct 09 '10 21:10

Noah R


2 Answers

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 "lass", 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

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 so simple...

like image 124
Brent Writes Code Avatar answered Oct 26 '22 13:10

Brent Writes Code


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'.

like image 30
cschol Avatar answered Oct 26 '22 12:10

cschol