如何打破从文本文件中读取的while循环

时间:2016-02-04 18:17:55

标签: python python-3.x

如果在文本文件中找不到输入中的任何单词,我希望循环中断,到目前为止我有:

import re
TypeFood = input("What food would you like to order?")
words = TypeFood.split()
with open("HungryHorseMenu.txt", "r") as f:
    for line in f:
        if any(word.lower() in re.findall('\w+', line.lower()) for word in words):
            splitted_line = line.split(',')
            print(splitted_line[0])
        else:
            print("We do not serve what you would like to eat.")
            break

我的文字文件是:

Vegetarian pizza, 
Margarita pizza,   
Meat feast pizza, 
Spaghetti bolognese, pasta, italian
Spaghetti carbonara, pasta, italian
Tagliatteli, pasta, italian


Cheeseburger, american
Chicken burger, american
Veggie burger, american
Hot dog, american


Chicken curry, indian
Lamb curry, indian
Vegetable curry, indian

当我输入不在文本文件中的内容时,它确实会中断,但如果我输入文本文件中的内容,则会打印出菜单,但在最后打印时,我们无法提供您想要的内容。 e.g。

I would like pizza

输出:

Vegetarian pizza 
Margarita pizza   
Meat feast pizza
We do not serve what you would like to eat

3 个答案:

答案 0 :(得分:0)

您正在遍历每一行,当它到达不包含您的短语的第一行时,即使它找到了某些内容,它也会出错。你想要这样的东西:

import re
TypeFood = input("What food would you like to order?")
words = TypeFood.split()
with open("HungryHorseMenu.txt", "r") as f:
    found = False
    for line in f:
        if any(word.lower() in re.findall('\w+', line.lower()) for word in words):
            splitted_line = line.split(',')
            found = True
            print(splitted_line[0])
    if found==False:
        print("We do not serve what you would like to eat.")

答案 1 :(得分:0)

您可以将所有有效项目放入列表中。如果列表为空,表示没有有效项目,如果不为空,则打印所有有效项目。

import re
TypeFood = input("What food would you like to order?")
words = TypeFood.split()
with open("sample.csv", "r") as f:
    valid_items = list()
    for line in f:
        if any(word.lower() in re.findall('\w+', line.lower()) for word in words):
            splitted_line = line.split(',')
            valid_items.append(splitted_line[0])


    if not valid_items:
        print("We do not serve what you would like to eat")
    else:
        for item in valid_items:
            print(item)

输出:

python test.py                                           
What food would you like to order?pizza
Vegetarian pizza
Margarita pizza
Meat feast pizza

python test.py                                 
What food would you like to order?indian
Chicken curry
Lamb curry
Vegetable curry

python test.py                                  
What food would you like to order?canadian
We do not serve what you would like to eat

答案 2 :(得分:-1)

尝试反转验证:

for line in f:
    if !any(word.lower() in re.findall('\w+', line.lower()) for word in words):
        print("We do not serve what you would like to eat.")
        break
    else:
        splitted_line = line.split(',')
        print(splitted_line[0])