Day6.迭代器与生成器的应用

1.迭代器的应用
文件名:a,文件内容如下:

apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3

实现功能:cat a |grep apple
  要求1:定义迭代器函数cat
  要求2:定义迭代器函数grep
    要求3:模拟管道的功能,将cat的处理结果作为grep的输入

#定义阶段:定义两个生成器函数
def cat(filename):
    with open(filename,mode="r",encoding="utf8") as f:
        f.seek(0)
        while True:
            line = f.readline()
            if line:
                yield line.strip()
            else:
                break
def grep(x,y):
    for line in y:
        if x in line:
            # print(line.strip())
            yield line
#调用阶段:得到两个生成器对象
g1=cat("a.txt")
g2=grep("apple",g1)
#next的触发执行g2生成器函数
for i in g2:
    print(i) 

2.生成器的应用
把下述函数改成生成器的形式,执行生成器函数的到一个生成器g,然后每次g.send(url),打印页面的内容,利用g可以无限send(这个闭包函数是老师为了巩固以前知识,不使用该模板)

def get(url):
    def index():
      return urlopen(url).read()
    return index
from urllib.request import urlopen
def index():
    while True:
        url = yield
        print("%s的网页源代码是: " %url)
        print(urlopen(url).read())
g=index()
next(g)
g.send("http://www.baidu.com")
g.send("http://www.python.org")

 

posted @ 2017-04-12 15:46  这个新手不太冷°  阅读(171)  评论(1)    收藏  举报