我试图raw_input从用户获取,然后从该输入中找到所需的单词.如果所需的单词存在,则运行一个函数.所以我尝试.split拆分输入,但如何找到所需的单词是否在列表中.
完成这项工作非常简单.Python有一个in完全符合您需求的运算符.您可以查看字符串中是否存在单词,然后执行您想要执行的任何操作.
sentence = 'hello world'
required_word = 'hello'
if required_word in sentence:
# do whatever you'd like
Run Code Online (Sandbox Code Playgroud)
您可以in在此处查看运算符的一些基本示例.
根据您输入的复杂性或所需单词的复杂性,您可能会遇到一些问题.为了解决这个问题,您可能希望对所需的单词更具体一些.
我们以此为例:
sentence = 'i am harrison'
required_word = 'is'
Run Code Online (Sandbox Code Playgroud)
这个例子将评估True你是否要做,if required_word in sentence:因为从技术上讲,这些字母is是"哈里森"这个词的子串.
要解决这个问题,你只需要这样做:
sentence = 'i am harrison'
required_word = ' is '
Run Code Online (Sandbox Code Playgroud)
通过这个词之前和之后把空的空间会专门寻找所需的单词出现作为一个单独的词,而不是作为一个词的一部分.
但是,如果您可以匹配子字符串以及单词出现,那么您可以忽略我之前解释的内容.
如果有一组单词,如果其中任何一个是必需单词,那么我该怎么办?就像,所需的单词是"是"或"是".用户输入包含"是"或"是".
根据这个问题,实现看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
这利用了any操作员.只要在其中required_words找到至少一个单词,if语句将评估为true sentence.
| 归档时间: |
|
| 查看次数: |
518 次 |
| 最近记录: |