example-code-2e/17-it-generator/sentence_iter2.py

38 lines
749 B
Python
Raw Normal View History

"""
Sentence: iterate over words using the Iterator Pattern, take #2
WARNING: the Iterator Pattern is much simpler in idiomatic Python;
see: sentence_gen*.py.
"""
import re
import reprlib
RE_WORD = re.compile(r'\w+')
class Sentence:
def __init__(self, text):
self.text = text
def __repr__(self):
2021-05-21 23:56:12 +02:00
return f'Sentence({reprlib.repr(self.text)})'
def __iter__(self):
word_iter = RE_WORD.finditer(self.text) # <1>
return SentenceIter(word_iter) # <2>
2021-05-21 23:56:12 +02:00
class SentenceIter:
def __init__(self, word_iter):
self.word_iter = word_iter # <3>
def __next__(self):
match = next(self.word_iter) # <4>
return match.group() # <5>
def __iter__(self):
return self