• Python(函数式编程)


    函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计。函数就是面向过程的程序设计的基本单元。

    峰哥原创面向过程解释:

    函数的参数传入,是函数吃进去的食物,而函数return的返回值,是函数拉出来的结果,面向过程的思路就是,把程序的执行当做一串首尾相连的函数,一个函数吃,拉出的东西给另外一个函数吃,另外一个函数吃了再继续拉给下一个函数吃。。。

    例子:实现linux下类似  grep -rl 'root' /etc 的功能(搜索etc文件夹下,内容中含有‘root’的文件有哪些)

    #应用:grep -rl 'root' /etc
    import os
    def init(func):
        def wrapper(*args,**kwargs):
            g=func(*args,**kwargs)
            next(g)
            return g
        return wrapper
    #阶段一:递归地找文件的绝对路径,把路径发给阶段二
    @init
    def search(target):
        'search file abspath'
        while True:
            start_path=yield
            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)
                    target.send(file_path)
    #阶段二:收到文件路径,打开文件获取获取对象,把文件对象发给阶段三
    @init
    def opener(target):
        'get file obj: f=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):
        'read file'
        while True:
            filepath,f=yield
            for line in f:
                res=target.send((filepath,line))
                if res:
                    break
    
    #阶段四:收到一行内容,判断root是否在这一行中,如果在,则把文件名发给阶段五
    @init
    def grep(target,pattern):
        'grep function'
        tag=False
        while True:
            filepath,line=yield tag #target.send((filepath,line))
            tag=False
            if pattern in line:
                target.send(filepath)
                tag=True
    #阶段五:收到文件名,打印结果
    @init
    def printer():
        'print function'
        while True:
            filename=yield
            print(filename)
    
    start_path1=r'C:UsersAdministratorPycharmProjectspython5期a'
    start_path2=r'C:UsersAdministratorPycharmProjectspython5期a'
    g=search(opener(cat(grep(printer(),'root'))))
    
    print(g)
    # g.send(start_path1)
    g.send(start_path2)
  • 相关阅读:
    webmagic使用
    网站文件下载链接
    正则表达式
    JS 页面刷新或重载
    History
    【问题&解决】fonts/fontawesome-webfont.woff2 404 (Not Found)
    ckeditor的使用
    Windows Server 2012 R2 或 2016 无法安装 .Net 3.5.1
    自定义配置文件的读取
    MVC中上传文件大小限制的解决办法
  • 原文地址:https://www.cnblogs.com/zihe/p/7049004.html
Copyright © 2020-2023  润新知