自学Python4.9-生成器举例

自学Python之路-Python基础+模块+面向对象
自学Python之路-Python网络编程
自学Python之路-Python并发编程+数据库+前端
自学Python之路-django

自学Python4.9 - 生成器举例

举例1:监听文件输入(用户一边输入程序,一边可以监听输入的内容)

此时在file文件里面输入内容,在生成器执行里面可以看到file的内容,且后续一直为空,程序一直在执行,只是读出的数据是空。

进一步,如果line不为空才打印

f = open("file",encoding="utf-8")
while True:
    line = f.readline()
    if line:
        print(line)

进一步,取消执行器看到的空格

f = open("file",encoding="utf-8")
while True:
    line = f.readline()
    if line:
        print(line.strip())

如何用生成器实现:

def tail(filename):
      f = open(filename,encoding="utf-8")
      while True:
             line = f.readline()
             if line.strip(): 
                print(line.strip())
tail('file')

 打印监听每行字前面加******

 监听每行字如果有python才打印,  实现监听过滤功能。

举例2:处理文件,用户指定要查找的文件和内容,将文件中包含要查找内容的每一行都输出到屏幕

def check_file(filename,aim):
    with open(filename,encoding='utf-8') as f:   #句柄 : handler,文件操作符,文件句柄
        for i in f:
            if aim in i:
                yield i

g = check_file('test.01','生成器')
for i in g:
    print(i.strip()) 

 

 

 

将文件test.01里面含有"生成器"的行数打印出来:

举例3:写生成器,从文件中读取内容,在每一次读取到的内容之前加上‘***’之后再返回给用户

def check_file(filename):
    with open(filename,encoding='utf-8') as f:   #句柄 : handler,文件操作符,文件句柄
        for i in f:
            yield '***'+i

for i in check_file('test.01'):
    print(i.strip())

 

......

posted on 2019-03-21 16:32  CARLOS_KONG  阅读(373)  评论(0编辑  收藏  举报

导航