检查字符串是否包含在列表元素中

2024-05-23 20:49:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份可能发生的事件的样本清单:

incident = [
    "road", "free", "block", "bumper", "accident","robbery","collapse","fire","police","flood"]

我想看看一个句子里有没有这个词。你知道吗

“大楼着火了”

这应该返回true,因为列表中有fire,否则返回false。你知道吗

我试着用这个方法:

query = "@user1 @handler2 the building is on fire"

if any(query in s for s in incidentList):
    print("yes")
else:
    print("no")

但是它总是失败,因为它与whenquery = "fire"相反。你知道吗

编辑

如果event包含一个元素,比如:“street fight”,我希望它返回true,假设查询包含street或fight。 我该怎么解决这个问题?你知道吗


Tags: intruefreestreet事件queryblockfire
3条回答

希望这有帮助。。你知道吗

import sys
incident = ["road", "free", "block", "bumper", "accident","robbery","collapse","fire","police","flood", "street fight"]
sentence = "street is awesome"
sentence = sentence.split()
for word in sentence:       
    for element in incident:
        if word in element.split():
            print('True')
            sys.exit(0)

s引用事件列表中的每个事件,检查s是否在query中:

if any(s in query for s in incidentList):

and in situation when incident contains an element say: "street fight", i want it to return true assuming the query contains either street or fight. How do i fix this?

然后,要么改进incidentList以仅包含单个单词,要么还应拆分循环中的s

if any(any(item in query for item in s.split()) for s in incidentList):

你就快到了,只需要反过来做:

incident = [
    "road", "free", "block", "bumper", "accident","robbery","collapse","fire","police","flood"]

query = "@user1 @handler2 the building is on fire"

if any(s in query for s in incident):
    print("yes")
else:
    print("no")

这是有意义的,因为您需要检查incident(任何单词,包括fire)中的每个s(即fire)是否也在query中。你知道吗

你不想说query(也就是说,你的整个句子)是否在s(也就是像fire这样的词)

相关问题 更多 >