Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find keywords in text using python

Tags:

python

text

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.

like image 388
Dain Wareing Avatar asked Dec 18 '22 08:12

Dain Wareing


2 Answers

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'
like image 121
Cory Kramer Avatar answered Dec 20 '22 20:12

Cory Kramer


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

like image 44
mahendra kamble Avatar answered Dec 20 '22 20:12

mahendra kamble