Created
June 23, 2019 04:39
-
-
Save ianlini/3ef520409368bee1b7967c01dd264ce6 to your computer and use it in GitHub Desktop.
Read input word by word in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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