Reputation: 3255
I have a sample list of possible incident:
incident = [
"road", "free", "block", "bumper", "accident","robbery","collapse","fire","police","flood"]
and i want to check if a sentence has any of this words in it.
eg. "the building is on fire"
this should return true since the list has fire in it and return false if otherwise.
I tried doing it with this method :
query = "@user1 @handler2 the building is on fire"
if any(query in s for s in incidentList):
print("yes")
else:
print("no")
but it always fail as oppose to when query = "fire"
.
Edit
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?
Upvotes: 0
Views: 124
Reputation: 504
Hope this helps..
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)
Upvotes: 1
Reputation: 473863
s
refers to every incident in the list of incidents, check if s
is in query
instead:
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?
Then, either improve the incidentList
to contain individual words only, or you should also split the s
in the loop:
if any(any(item in query for item in s.split()) for s in incidentList):
Upvotes: 6
Reputation: 30813
You are almost there, just need to do it the reverse way:
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")
Which makes sense, because you want to check for every s
in incident
(any word, including fire
), if that s
(that is, fire
) is in query
too.
You do not want to say if query
(that is, your whole sentence) is in s
(that is, a word like fire
)
Upvotes: 3