2021-02-15 00:58:46 +01:00
|
|
|
"""
|
|
|
|
Sentence: iterate over words using a generator function
|
|
|
|
"""
|
|
|
|
|
|
|
|
# tag::SENTENCE_GEN[]
|
|
|
|
import re
|
|
|
|
import reprlib
|
|
|
|
|
|
|
|
RE_WORD = re.compile(r'\w+')
|
|
|
|
|
|
|
|
|
|
|
|
class Sentence:
|
|
|
|
|
|
|
|
def __init__(self, text):
|
|
|
|
self.text = text
|
|
|
|
self.words = RE_WORD.findall(text)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return 'Sentence(%s)' % reprlib.repr(self.text)
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for word in self.words: # <1>
|
|
|
|
yield word # <2>
|
2021-09-16 03:48:08 +02:00
|
|
|
# <3>
|
2021-02-15 00:58:46 +01:00
|
|
|
|
|
|
|
# done! <4>
|
|
|
|
|
|
|
|
# end::SENTENCE_GEN[]
|