首页 > 代码库 > python_class21
python_class21
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: 3.5 @author: morgana @license: Apache Licence @contact: vipmorgana@gmail.com @site: @software: PyCharm @file: notes.py @time: 2017/6/19 上午8:51 """ # 1.yield的表达式形成的应用 # 2.面向过程编程:grep -rl ‘root‘ /etc # 3.递归 # 4.内置函数 # # 三元表达式:res=True if 1>2 else False # 列表解析:[i for i in range(10) if i>5] # 生成器表达式:(i for i in range(10) if i>5) # 生成器:函数函数内部有yield关键字,那函数执行的结果就是生成器 # def init(func): # def warpper(*args,**kwargs): # g=func(*args,**kwargs) # next(g) # return g # return warpper # # @init # def foo(): # print(‘starting‘) # while True: # x=yield # print(‘value: ‘,x) #send的效果 #1.先从为暂停位置的那个yield传一个值,然后yield会把值赋值x #2:与next的功能一样 # g=foo() # print(g) # next(g) # print(‘=‘*30) # print(g.send(1)) # print(‘=‘*30) # print(g.send(2)) # print(g.send(3)) # print(g.send(3)) # # @init # def eater(name): # print(‘%s read to eat ‘ %name) # food_list=[] # while True: # food=yield food_list # food_list.append(food) # print("%s start to eat %s" %(name,food)) # # # # e=eater(‘alex‘) # e.send("shit") # e.send("dog shit") # # def init(func): # def warpper(*args,**kwargs): # g=func(*args,**kwargs) # next(g) # return g # return warpper # # # @init # def eater(name): # print("%s eat " %(name)) # food_list=[] # while True: # food=yield food_list # food_list.append(food) # print("%s eat %s" %(name,food)) # # # def make_shit(people,n): # for i in range(n): # people.send("shit %s" %i) # # e=eater("alex") # make_shit(e,5) #1.找到文件 #2.把文件找到 绝对路径 send()-》 #3.遍历文件内容 #判断 import os def init(func): def warpper(*args,**kwargs): g=func(*args,**kwargs) next(g) return g return warpper # 阶段一:递归找文件绝对路径,把路径发给阶段二 def search(target, start_path): ‘serch file abpath‘ g = os.walk(start_path) for par_dir, _, files in g: # print(par_dir,files) for file in files: #file_path =r‘%s\%s‘ % (par_dir, file) file_path = ‘%s%s‘ % (par_dir, file) #print(file_path) target.send(file_path) # 阶段二:收到文件路径,打开文件获取对象,把文件对象发给阶段三 @init def opener(target): ‘get file obj open(filepath)‘ while True: file_path = yield with open(file_path, encoding=‘utf-8‘) as f: target.send((file_path,f)) # 阶段三:收到文件对象,for循环读取文件的每一行内容,把每一行内容发给阶段四 @init def cat(target): # ‘cat file‘ while True: file_path, f = yield for line in f: target.send((file_path,line)) # 阶段四:收到一行内容,判断root是否在这一行中,如果在,则把文件名发给阶段五 @init def grep(target, pattern): while True: file_path, line = yield if pattern in line: target.send(file_path) # 阶段五:收到文件名打印结果 @init def printer(): # ‘print function‘ while True: filename = yield print(filename) start_path =‘/Users/shuanggai/PycharmProjects/git/python/20170619_yield_recursion/homework/‘ search(opener(cat(grep(printer(),‘root‘))),start_path)
python_class21
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。