import re #后面省略书写
RE_WORD = re.compile('\w+')#后面省略书写
class Sentence1:
def __init__(self,text):
self.text = text
self.words = RE_WORD.findall(text)#返回匹配列表
def __getitem__(self,index):
return self.words[index]
s1 = Sentence1('"the time make god and gost" mir ding said') #可遍历输出
2.利用__iter__()调用 自定义类型 的生成器函数
class Sentence2:
def __init__(self,text):
self.text = text
self.words = RE_WORD.findall(text)
def __iter__(self):
return iter(self.words)#利用列表的__iter__返回生成器
s2 = Sentence2('"the time make god and gost" mir ding said')#可遍历输出
3.典型的方法(啰嗦但是却标准的无可反驳,不是懒人的做法)
class Sentence3:
def __init__(self,text):
self.text = text
self.words = RE_WORD.findall(text)
def __iter__(self):
return Sentence3Iterator(self.words)#利用对应的生成器类,实例化生成器对象
class Sentence3Iterator:
def __init__(self,words_list):
self.words_list = words_list
self.pos = 0
def __next__(self):
try:
word = self.words_list[self.pos]
except IndexError:
raise StopIteration()
self.pos +=1
return word
def __iter__(self):
return self
s3 = Sentence3('"the time make god and gost" mir ding said')#可遍历输出
4.利用生成器函数yield 简单高效
class Sentence4:
def __init__(self,text):
self.text = text #拷贝的引用,并不占用太多内存
self.words = RE_WORD.findall(text)#建立所有单词的列表,占用大量内存,接下来优化
def __iter__(self):
for word in self.words:
yield word
return #可有可无
s4 = Sentence4('"the time make god and gost" mir ding said')#可遍历输出
5.惰性实现,节省内存
class Sentence5:
def __init__(self,text):
self.text = text
def __iter__(self):
for word in RE_WORD.finditer(self.text):#finditer返回一个迭代器
yield word.group()
return
s5 = Sentence5('"the time make god and gost" mir ding said')#可遍历输出
6.利用生成器表达式进一步简化,生成器表达式返回一个新的生成器
class Sentence6:
def __init__(self,text):
self.text = text
def __iter__(self):
return ( word.group() for word in RE_WORD.finditer(self.text)) #语法糖跟生成器函数一样
s6 = Sentence6('"the time make god and gost" mir ding said')#可遍历输出
7.yield from (整个迭代器"搬过来"用)
class Sentence7:
def __init__(self,text,text_added):
self.text = text
self.text_added = text_added
def __iter__(self):
yield from ( word.group() for word in RE_WORD.finditer(self.text))
yield from ( word.group() for word in RE_WORD.finditer(self.text_added))
s7 = Sentence7('"the time make god and gost" mir ding said',"conclusion: i love time")#可遍历输出