检查list元素中是否包含字符串

时间:2016-03-20 15:47:01

标签: python

我有可能发生的事件的样本列表:

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

我想检查句子中是否包含任何单词。

例如。 “这座建筑着火了”

这应该返回true,因为列表中有火,否则返回false。

我试过这种方法:

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

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

但它始终失败,与query = "fire"时相反。

修改

并且在事件包含元素的情况下说:“街头斗争”,我希望它返回true,假设查询包含街道或战斗。 我该如何解决这个问题?

3 个答案:

答案 0 :(得分:5)

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

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

并且在事件包含元素的情况下说:"街头战斗",我希望它返回true,假设查询包含街道或战斗。我该如何解决这个问题?

然后,改进incidentList仅包含单个单词,或者您还应该在循环中拆分s

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

答案 1 :(得分:2)

你几乎就在那里,只需要以相反的方式去做:

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")

这是有道理的,因为您要检查s中的每个incident(任何字,包括fire),如果s(即{{} 1}})也在fire

想要说query(即您的整个句子)是否在query中(即s之类的字)

答案 2 :(得分:1)

希望这会有所帮助..

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)