如何在Python 3.3.0中测试没有输入

时间:2013-04-30 16:45:40

标签: python python-3.x

目前,我正在开发一个Python程序,它返回在多行输入中出现的单词,最后一行是字符串“###”。

poetry  = []
max = 0
maxitem = None
while True:
 poetry.append(input().lower().split())
for x in poetry:
    count =  poetry.count(x)
if count > max:
    max = count
    maxitem = x
    print(maxitem)

现在,我遇到的主要问题是我在while循环体中得到的EOF错误。据我所知,其背后的原因是它不断要求新的输入线,但它没有。我不知道如何纠正这个问题。任何有关该计划其余部分的帮助也将受到赞赏。

2 个答案:

答案 0 :(得分:4)

请勿使用input()来读取数据,而是使用sys.stdin

for line is sys.stdin:
    poetry.append(line.lower().split())

这将从stdin文件句柄读取行直到关闭,而不会抛出EOF异常。如果stdin开始关闭,则循环体将不会执行。

答案 1 :(得分:3)

按照Martijn Pieters的建议使用sys.stdin是这里的方法,但为了完整起见,您可以继续使用input()。您只需捕获EOFError异常并退出循环:

while True:
    try:
        poetry.append(input().lower().split())
    except EOFError:
        break