Skip to content

Instantly share code, notes, and snippets.

@ianlini
Created June 23, 2019 04:39
Show Gist options
  • Save ianlini/3ef520409368bee1b7967c01dd264ce6 to your computer and use it in GitHub Desktop.
Save ianlini/3ef520409368bee1b7967c01dd264ce6 to your computer and use it in GitHub Desktop.
Read input word by word in Python
class WordReader(Iterator):
def __init__(self, fp=sys.stdin):
self.fp = fp
def __next__(self):
word = ''
while True:
c = self.fp.read(1)
if c is None:
if word:
return word
else:
raise StopIteration
elif c == ' ' or c == '\n':
if word:
return word
else:
word += c
def get_int(self):
return int(next(self))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment