如何在Python中检查一个句子是否包含某个单词,然后执行一个操作?
假设我向用户询问原始输入,他们说:“这是一条消息。”如果该原始输入包含单词“消息”,它将在此之后执行操作。我能看看如何做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据@knitti的评论,问题是你需要先将句子分成单词,然后检查:
否则,如果你有句子“That one is a classic”并且你试图检查它是否包含这个单词“lass”,它会错误地返回 True。
当然,这仍然不完美,因为那样你可能不得不担心诸如删除标点符号之类的事情(例如,……等),因为否则句子“That one is a classic”。搜索“classic”时仍会返回 False(因为末尾有句点)。与其重新发明轮子,这里有一篇关于从 Python 句子中剥离标点符号的好文章:
从字符串中删除标点符号的最佳方法
还需要考虑区分大小写,因此您可能需要先将
raw_input
结果和搜索词更改为小写进行搜索。您只需使用str
类上的lower()
函数即可轻松实现此目的。这些问题总是显得那么简单……
Going based on the comment by @knitti, the problem is that you need to split up the sentence into words first, then check:
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 thelower()
function on thestr
class.These problems always seem so simple...
这当然是一个非常简单的示例:
如果需要将不同的单词映射到不同的操作,那么您可以执行以下操作:
注意,这还为输入不包含任何以下内容的情况定义了默认操作触发词。
有关上述映射习惯用法的更多详细信息,请参阅此处,这实际上是Python的方式实现“switch 语句”。
This is of course a very simple example:
If you are required to map different words to different actions, then you could do something like this:
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'.
只需写:
term = 您想要在输入中检查的内容或其他内容
y = input function # 你要输入的内容 注:y 不是必须的 你可以拿任何你想要的!
然后写
if term in y: # 检查 y(input) 是否包含你想要检查的单词
你想要做的事情
就是这么简单
Just write :
term = what you want to be checked in input or something
y = input function # what you want to be inputted note: taking y as input is not necessary You can take whatever you want!
then write
if term in y: # checks whether y(input) contain the word you wanted to be checked
what you want to do
see it's just that simple