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

时间:2017-04-12 12:26:56

标签: python text

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

例如,如果我输入“我如何找到伦敦”,它会看到伦敦的字样并找到。

如何使用数组使代码看起来更清晰。

#!/bin/bash
while :
do
    source /tmp/.myvars
    if [[ ${RUNPROCQ} != "false" ]]; then
        php yii process-queue
    fi
    sleep 0.5
done

所以我只想知道如何在用户输入中找到数组中的单词。

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

3 个答案:

答案 0 :(得分:5)

你走在正确的轨道上。第一个变化是您的字符串文字需要在引号内,例如'London'。其次,你的in向后,你应该使用element in sequence,所以在这种情况下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")

如果要进行子串匹配,可以将其更改为

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'

答案 1 :(得分:1)

你可以试试这个:

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。

答案 2 :(得分:0)

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

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

相关问题