在Python中检查字符串是否包含列表中的元素时出错?

在Python中检查字符串是否包含列表中的元素时出错?,python,list,any,Python,List,Any,因此,我尝试使用any()函数搜索用户输入的字符串,看看它是否包含列表中的任何元素: # takes the user input i = raw_input(">>> ") e = i.lower() af.inp.append(e) # greeting section if any(x in e for x in af.x): af.greeting() 名单: 所以基本上我遇到了一个问题,如果我输入任何包含列表中任何字符的字符串,它将返回问候函数 这是一个问

因此,我尝试使用any()函数搜索用户输入的字符串,看看它是否包含列表中的任何元素:

# takes the user input
i = raw_input(">>> ")
e = i.lower()
af.inp.append(e)

# greeting section
if any(x in e for x in af.x):
    af.greeting()
名单:

所以基本上我遇到了一个问题,如果我输入任何包含列表中任何字符的字符串,它将返回问候函数

这是一个问题,因为如果我输入“Shit”而不是“Hi”,它将运行问候功能。我想我可能使用了错误的函数来搜索用户输入文本中的特定整词或字符串,而不是单词的一部分:例如“S'hi't”而不是“hi”

有人知道如何解决这个问题,或者我是否有其他方法可以搜索整个单词或字符串


p、 为了澄清我理解为什么使用any函数会发生这种情况,我只是想知道是否有任何方法可以解决这个问题或使用不同的方法。

如果您想检查列表
x
中是否存在您的单词,那么您需要拆分您的输入,然后使用
any

i = raw_input(">>> ")
e = i.lower().split()
af.inp.append(e)

# greeting section
if any(x in e for x in af.x):
    af.greeting()
或者,您可以简单地将您的文字放入
集合
对象中,然后使用
集合。交叉
方法:

x = {"hello", "hi", "hey"}
if x.intersections(af.x):
    af.greeting()
str.split()!你好吗?
差不多。我想你应该在这里用正则表达式。范例-

import re
if any(re.search(r'\b{}\b'.format(x),e) for x in af.x):
    af.greeting()
示例/演示-

>>> import re
>>> e = 'hey! how are you?'
>>> xx = ["hello", "hi", "hey"]
>>> if any(re.search(r'\b{}\b'.format(x),e) for x in xx):
...     print('Hello to you too!')
...
Hello to you too!
>>> e = 'shit'
>>> if any(re.search(r'\b{}\b'.format(x),e) for x in xx):
...     print('Hello to you too!')
...
>>>
>>> e = 'hi you'
>>> if any(re.search(r'\b{}\b'.format(x),e) for x in xx):
...     print('Hello to you too!')
...
Hello to you too!

你必须解释什么是
af
af.inp
af.x
。“af”是包含我正在运行的所有列表的模块。。。af.x是包含所有问候语的列表(我在初始注释中包含了这部分代码),af.inp是我将用户输入推送到其中以保存的列表。所有这些对问题都不重要。为什么要包括它?我想我会为上下文多出一行代码?如果多读一行代码对你来说太麻烦了,那么这里有6行代码。你如何努力回答投诉?尝试。你的例子不是这些。我抱怨的不是读额外一行的努力,而是你缺乏努力。现在,当我尝试输入一个不包含问候语列表中字符的单词时,我遇到了以下错误:回溯(最近一次调用):文件“main.py”,第30行,在af.wu的elif e中:TypeError:unhabable type:'list'@TreyTaylor你是怎么做到的?当您在
集合中使用列表时,会发生此错误。我会排除答案,但我还没有15个声誉:(对不起。@TreyTaylor是的,没关系,您可以在达到15;)谢谢,我想我会试试这个!
>>> import re
>>> e = 'hey! how are you?'
>>> xx = ["hello", "hi", "hey"]
>>> if any(re.search(r'\b{}\b'.format(x),e) for x in xx):
...     print('Hello to you too!')
...
Hello to you too!
>>> e = 'shit'
>>> if any(re.search(r'\b{}\b'.format(x),e) for x in xx):
...     print('Hello to you too!')
...
>>>
>>> e = 'hi you'
>>> if any(re.search(r'\b{}\b'.format(x),e) for x in xx):
...     print('Hello to you too!')
...
Hello to you too!