Noah R Noah R - 1 year ago 172
Python Question

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

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?

Answer Source

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

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:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download