2021-02-15 00:58:46 +01:00
|
|
|
"""
|
|
|
|
Sentence: iterate over words using a generator function
|
|
|
|
"""
|
|
|
|
|
|
|
|
# tag::SENTENCE_GEN2[]
|
|
|
|
import re
|
|
|
|
import reprlib
|
|
|
|
|
2021-05-21 23:56:12 +02:00
|
|
|
RE_WORD = re.compile(r'\w+')
|
2021-02-15 00:58:46 +01:00
|
|
|
|
|
|
|
|
|
|
|
class Sentence:
|
|
|
|
|
|
|
|
def __init__(self, text):
|
|
|
|
self.text = text # <1>
|
|
|
|
|
|
|
|
def __repr__(self):
|
2021-05-21 23:56:12 +02:00
|
|
|
return f'Sentence({reprlib.repr(self.text)})'
|
2021-02-15 00:58:46 +01:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for match in RE_WORD.finditer(self.text): # <2>
|
|
|
|
yield match.group() # <3>
|
|
|
|
|
|
|
|
# end::SENTENCE_GEN2[]
|