Reputation: 57
Currently, I'm working on a Python program that returns the word that occurs most times in however many lines of input, with the last line being the string "###".
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)
Now, the main problem I have is the EOF error I get in the body of the while loop. As far as I can tell, the reason behind this is that it continually calls for a new line of input, but it gets none. I do not know how to rectify this. Any help with the rest of the program would be appreciated as well.
Upvotes: 0
Views: 621
Reputation: 208455
Using sys.stdin
as suggested by Martijn Pieters is the way to go here, but for completeness here is how you could continue to use input()
. You just need to catch the EOFError
exception and exit the loop:
while True:
try:
poetry.append(input().lower().split())
except EOFError:
break
Upvotes: 2
Reputation: 1121634
Don't use input()
to read data, use sys.stdin
instead:
for line is sys.stdin:
poetry.append(line.lower().split())
This will read lines from the stdin
file handle until closed, without throwing EOF exceptions. The loop body won't execute at all if stdin
starts closed.
Upvotes: 4