如何在python中搜索用户输入关键字

时间:2016-02-10 09:04:49

标签: python file python-3.x input

如何搜索用户输入并查找特定关键字,然后在文本文件中搜索此关键字?

这是我到目前为止所做的:

foods = str(input("what takeaway would you like today go sir/madame reply with one word answers"))

with open("pizza.txt", "r") as f:              
    searchlines = f.readlines()

for i, line in enumerate(searchlines):      
    if foods in line:  
            print(line)

1 个答案:

答案 0 :(得分:0)

请阅读https://stackoverflow.com/help/mcve。作为完整和可执行的手段(如果可能的话,它在这里),所有需要的数据来说明问题应该在发布的代码中。

您的第一句话意味着您希望限制用户对可能找到的食物的输入。以下是这样做的。

dishes = (
    "Patriot Pizza: yellow cheese, tomato, olives",
    "Tropical treat: guava cheese, pineapple, mango",
)

foods = ('cheese', 'tomato', 'olives', 'guava', 'pineapple', 'mango')
print(foods)

food = ''
while food not in foods:
    food = input('Enter one of the foods listed above: ')

for i, dish in enumerate(dishes):
    if food in dish:
        print(i, dish)