0

我正在尝试将用户提供的单词(例如"orange")与我在文本文件中的单词列表进行比较,如下所示:

菜单.txt

apple 
banana
orange
grape
mango

用户输入来自easygui.enterbox. 我从来没有得到我期望的结果,因为它很难比较字符串。这是我的代码。

import easygui     

count = 0
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
    content = f.readlines()
    for item1 in content:
        if item1 == dish :
            easygui.msgbox("order taken.thankyou")
            count = count + 1
            continue
        if count == 0 :
            easygui.msgbox("plz order some other item")
4

3 回答 3

1

f.readlines()返回以行结尾的项目。你想要.strip()换行符和额外的空格。有else:forfor循环;你想在这里使用它;如果找到匹配项,您break将退出循环;else报告错误。此外,缩进4个空格,这是标准。

import easygui     

dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
    content = f.readlines()
    for item1 in content:
        item1 = item1.strip()
        if item1 == dish:
            easygui.msgbox("order taken. thankyou")
            # it can match 1 dish only; so we can exit now
            break

    else:
        easygui.msgbox("plz order some other item")
于 2015-02-22T18:04:57.410 回答
0

首先你不需要readlines()遍历你的行,其次你需要strip在比较之前你的行!因为那些包含换行符\n

import easygui     
count = 0
dish = easygui.enterbox("enter your favourite dish:")
with open("menu.txt") as f:
      for item1 in f:
            if item1.strip() == dish :
                  easygui.msgbox("order taken.thankyou")
                  count = count + 1
            continue
      if count == 0 :
                  easygui.msgbox("plz order some other item") 
于 2015-02-22T18:04:43.323 回答
0

您可能需要将 .strip() 添加到 item 和 disc 中,以确保所有空格或行尾符号都不是字符串的一部分

于 2015-02-22T18:07:50.083 回答