首页 > 代码库 > 迭代器的应用

迭代器的应用

迭代器的应用  

文件名:a.txt,文件内容如下:
    apple 10 3
    tesla 100000 1
    mac 3000 2
    lenovo 30000 3
    chicken 10 3
  实现功能:cat a.txt |grep apple
    要求1:定义迭代器函数cat
    要求2:定义迭代器函数grep
    要求3:模拟管道的功能,将cat的处理结果作为grep的输入

 

追加的代码文件:

#追加的代码with open(‘a.txt‘,‘a+‘,encoding=‘utf-8‘) as f:    while True:        dl = input(‘请输入你的内容(q退出):‘)        if dl.lower() ==‘q‘:            break        else:            f.write(dl+‘\n‘)

  

查看动态追加的代码:

文件是atxtimport time########动态查看添加文件的内容 catdef get(acth):    with open(acth,‘a+‘,encoding=‘utf-8‘) as f:        f.seek(0,2)        while True:            line = f.readline()            if not line:                time.sleep(.3)                # print(‘-------->‘)                continue            else:                yield line.strip()g = get(‘a.txt‘)# print(next(g))for line in g:    print(line)########动态查看文件追加过滤出来的内容  grupdef get(acth):    with open(acth,‘a+‘,encoding=‘utf-8‘) as f:        f.seek(0,2)        while True:            line = f.readline()            if not line:                time.sleep(.3)                # print(‘-------->‘)                continue            elif ‘apple‘ in line:                yield lineg = get(‘a.txt‘)# print(next(g))# for line in g:#     print(line)while True:    try:        ne = next(g)        print(ne.strip())    except StopIteration:        break###########管道流.....#定义阶段def get(acth):    with open(acth,‘a+‘,encoding=‘utf-8‘) as f:        f.seek(0,2)        while True:            line = f.readline()            if not line:                time.sleep(.3)                continue            else:                yield line.strip()def grup(pattern,lines):    for line in lines:        if pattern in line:            yield line#调用阶段g = get(‘a.txt‘)g1 = grup(‘apple‘,g)#next触发执行g1生成器函数for i in g1:    print(i)

  

 

生成器的使用

把下述函数改成生成器的形式,执行生成器函数的到一个生成器g,然后每次g.send(url),打印页面的内容,利用g可以无限send

from urllib.request import urlopendef get():    print(‘strat‘)    while True:        url = yield        print(urlopen(‘%s‘%url).read())g = get()g.__next__()g.send(‘http://www.baidu.com‘)g.send(‘http://www.taobao.com‘)

  

 

迭代器的应用