2016-02-04 52 views
1

我希望循環打破,如果任何來自輸入的話都沒有在文本文件中找到讀書,所以到目前爲止,我有:如何打破while循環從文本文件

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 

當我輸入的東西是不是在文本文件時,它不會打破,但如果我輸入的東西是文本文件,它打印出菜單,而且在最後打印我們不提供你想要什麼。 例如

I would like pizza 

輸出:

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

回答

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.") 
+0

這工作的感謝,但請你加我一些意見,解釋你添加的行做的,因爲我是個初學者,我不明白他們在做什麼。 – Thy

-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]) 
+0

除''以外使用'not'邏輯被破壞。嘗試輸入「披薩」,它會讓你的「我們不......」,這是不正確的。 – haifzhan

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