我正在尝试从用户那里获取 raw_input
,然后从该输入中找到所需的单词。如果所需的词存在,则函数运行。所以我尝试了 .split
来拆分输入,但我如何找到所需的单词是否在列表中。
最佳答案
完成这件事真的很简单。 Python 有一个 in
运算符,可以完全满足您的需要。您可以查看某个单词是否出现在字符串中,然后执行您想要执行的任何其他操作。
sentence = 'hello world'
required_word = 'hello'
if required_word in sentence:
# do whatever you'd like
您可以看到 in
运算符的一些基本示例的实际应用 here .
根据您输入的复杂程度或所需单词的复杂程度,您可能会遇到一些问题。为了解决这个问题,您可能需要更具体地使用所需的词。
让我们以此为例:
sentence = 'i am harrison'
required_word = 'is'
如果您执行if required_word in sentence:
,此示例将评估为True
,因为从技术上讲,字母是
是“哈里森”这个词。
要解决这个问题,您只需执行以下操作:
sentence = 'i am harrison'
required_word = ' is '
通过在单词前后放置空格,它将专门查找所需单词作为单独单词而不是单词的一部分的出现。
但是,如果您对匹配的子字符串以及单词出现没有问题,那么您可以忽略我之前解释的内容。
If there's a group of words and if any of them is the required one, then what should I do? Like, the required word is either "yes" or "yeah". And the input by user contains "yes" or "yeah".
根据这个问题,一个实现看起来像这样:
sentence = 'yes i like to code in python'
required_words = ['yes', 'yeah']
^ ^ ^ ^
# add spaces before and after each word if you don't
# want to accidentally run into a chance where either word
# is a substring of one of the words in sentence
if any(word in sentence for word in required_words):
# do whatever you'd like
这使用了 any
运算符。只要在 sentence
中找到 required_words
中的至少一个单词,if 语句就会评估为真。
关于python - 从句子中查找并选择所需的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39108452/