如何使用python在文本中查找关键字

如何使用python在文本中查找关键字,python,text,Python,Text,作为项目的一部分,我必须能够识别用户输入的关键字 例如,如果我键入“how to I find London”,它将看到单词London and find 如何使用数组使代码看起来更干净 city = [London, Manchester, Birmingham] where = input("Where are you trying to find") if(city in where): print("drive 5 miles") else: print("I'm

作为项目的一部分,我必须能够识别用户输入的关键字

例如,如果我键入“how to I find London”,它将看到单词London and find

如何使用数组使代码看起来更干净

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")
所以我只想知道如何从用户输入中的数组中查找单词


这不是项目,而是一种类似的方式。

您走在了正确的轨道上。第一个变化是字符串文字必须位于引号内,例如
“London”
。其次,您的
中是向后的,您应该按顺序使用
元素
,因此在本例中,
在城市中的位置

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")
如果要进行子字符串匹配,可以将其更改为

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")
这将接受
where
类似

'I am trying to drive to London'
您可以尝试以下方法:

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")
请注意对代码的细微更改

如果接收到的数组中的任何值为true,则any方法返回true。因此,我们创建一个数组,搜索用户输入中的每个城市,如果其中任何一个为true,则返回true

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")

它将检查用户输入是否存在于列表中

单词London和find-为什么是“find”?如果我输入了“伯明翰伦敦”?可能是重复的感谢你的帮助,这似乎是工作great@CoryKramer:回答得好!!一个建议
if any(我在where for i in city):
应该是
if any(我在where for i in city):
对吗?由于没有提到python版本,那么2.x呢?应该使用原始输入而不是输入?!如果您离开内部列表,
[]
它将在传递到
任何
功能之前评估所有城市。如果删除它们,则
any
中的表达式是生成器表达式,在找到性能的第一个匹配项时可能会短路。这是真的,我将更新我的答案,感谢您的建议!