2016-03-20 38 views
0

我有可能事件的样本列表:检查字符串包含在列表元素

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假设查询包含任何街道或战斗。 我该如何解决这个问题?

+4

应该而不是它在查询'而不是? – alecxe

+0

当像'broad'这样的单词出现时,您是否可以匹配'road'?如果用户名包含诸如'@ firefighter'之类的事件词,该怎么办?你不想不区分大小写吗?现在,“警察”不会被发现...... –

+0

@TimPietzcker这是真的,但我可以让所有的事情小写。 –

回答

5

s是指在事件列表中每一个事件,检查是否squery代替:

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): 
+0

plz,请参阅编辑。谢谢 –

+0

@ belvi好的,请参阅最新的答案。 – alecxe

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

,因为你要检查每一个sincident这是合理的,(任何字,包括fire),如果s(即fire)也在query

想说如果query(也就是你的整个句子)是s(即,像fire一个字)

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) 
相关问题