[英]Check if string is contained in list element
我有一個可能的事件的示例列表:
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"
相反時失敗。
編輯
並且在事件包含元素說:“ street fight”的情況下,假設查詢包含街道或戰斗,我希望它返回true。 我該如何解決?
s
引用事件列表中的每個事件,請檢查s
是否在query
:
if any(s in query for s in incidentList):
並且在事件包含元素說:“ street fight”的情況下,假設查詢包含街道或戰斗,我希望它返回true。 我該如何解決?
然后,要么將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
每個s
(任何單詞,包括fire
),如果該s
(即fire
)也在query
。
你不想說,如果query
(也就是你的整個句子)是s
(即,像一個字fire
)
希望這可以幫助..
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.