0

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?

3
  • 4
    Should not it be s in query instead? Commented Mar 20, 2016 at 15:47
  • Are you OK with matching road when words like broad are present? What if a username contains one of the incident words like @firefighter? Wouldn't you want to be case-insensitive? Right now, Police would not be found... Commented Mar 20, 2016 at 15:51
  • @TimPietzcker that's true, but i can just make the everything lower case then. Commented Mar 20, 2016 at 15:55

3 Answers 3

6

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):
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.