迭代器的应用,管道流筛选

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

 1 def cat(file):     #定义阅读文件内容的函数
 2     with open(file,"r") as f:
 3         while True:
 4             try:
 5                 line = f.readline()  #阅读文件一行一行的读
 6                 yield line          #返回每行的值
 7             except StopIteration:
 8                 break
 9 
10 def grep(pattern,lines):   #定义筛选函数
11     for line in lines:     #遍历文件内容的每一行
12         if pattern in line:    #满足筛选条件,返回筛选值
13             yield line
14 
15 lines = cat("a.txt")  #生成阅读文件内容的迭代器
16 result = grep("apple",lines)  #生成筛选值的迭代器
17 for i in result:  #遍历筛选值,打印结果
18     print(i)



原文地址:https://www.cnblogs.com/domestique/p/6701082.html