Dain Wareing
Dain Wareing

Reputation: 63

how to find keywords in text using python

As part of a project I have to be able to identify keywords that a user would input.

For example if I type "how to i find London" it would see the words London and find.

How would I do this using an array to make the code look cleaner.

city = [London, Manchester, Birmingham]
where = input("Where are you trying to find")
  if(city in where):
    print("drive 5 miles")
  else:
    print("I'm not to sure")

So I just want to know how do I find words from an array within a user input.

This isn't the project but a similar way of doing it.

Upvotes: 6

Views: 11988

Answers (3)

DSLima90
DSLima90

Reputation: 2838

You can try this:

cities = ['London', 'Manchester', 'Birmingham']
where = input("Where are you trying to find")
    if(any(city in where for city in cities)):
        print("drive 5 miles")
    else:
        print("I'm not to sure")

Note the minor changes to your code.

The any method returns true if ANY of the values in the received array are true. So we create an array searching for every city in the user input, if any of then is true, it return true.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

You are on the right track. The first change is that your string literals need to be inside of quotes, e.g. 'London'. Secondly you have your in backwards, you should use element in sequence so in this case where in cities.

cities = ['London', 'Manchester', 'Birmingham']
where = input("Where are you trying to find")
if where in cities:
    print("drive 5 miles")
else:
    print("I'm not to sure")

If you want to do substring matching, you can change this to

cities = ['London', 'Manchester', 'Birmingham']
where = input("Where are you trying to find")
if any(i in where for i in cities ):
    print("drive 5 miles")
else:
    print("I'm not to sure")

This would accept where to be something like

'I am trying to drive to London'

Upvotes: 8

mahendra kamble
mahendra kamble

Reputation: 1395

cities = ['London', 'Manchester', 'Birmingham']
where = raw_input("Where are you trying to find")
for city in cities:
    if city in where:
        print("drive 5 miles")
        break
else:
    print("I'm not to sure")

It will check user input is present in a list or not

Upvotes: 2

Related Questions