zoukankan      html  css  js  c++  java
  • CDays2 习题一 (改进函数)及相关内容解析。Python 基础教程

    在文中grep实现例子中,没有考虑子目录的处理,因为如果直接open目录进行读操作会出现错误,所以要求读者修改这个示例代码以便考虑到子目录这种特殊情况,然后把最后探索出的 cdcGrep()嵌入 pycdc-v0.5.py 实现完成版本的 PyCDC。

    根据CDays-2 中的源码,我们可以知道他列出了所有文件,并没有列出子目录。

    根据我们在之前做光盘遍历的经验,我们重写cdcGrep( )

    根据path中的方法isdir,我们可以根据os.path.isdir( ) 的返回值确定是否为目录。

    def cdcGrep(cdcpath,keyword):
        '''光盘信息文本关键词搜索函式
        @note: 使用最简单的内置字串匹配处理来判定是否有关键词包含
        @param cdcpath: 包含*.cdc 文件的目录
        @param keyword: 搜索的关键词
        @return: 组织匹配好的信息到字典中导出成 searched.dump 文件
        @todo: 可结合搜索引擎进行模糊搜索!
        '''
        expDict = {}
        filelist = os.listdir(cdcpath)          # 搜索目录中的文件
        cdcpath=cdcpath+"/"
        for cdc in filelist:                    # 循环文件列表
            if os.path.isdir(cdcpath+cdc):
                cdcGrep(cdcpath+cdc,keyword) # 若是子目录,则递归调用完成查找
            else:
                cdcfile = open(cdcpath+cdc)         # 拼合文件路径,并打开文件
                for line in cdcfile.readlines():    # 读取文件每一行,并循环
                    if keyword in line:             # 判定是否有关键词在行中       
                        #print line                  # 打印输出
                        expDict[cdc].append(line)
        #print expDict
        pickle.dump(expDict,open("searched.dump","w"))
  • 相关阅读:
    SSH整合简述一
    错误:找不到类org.springframework.web.context.ContextLoaderListener
    Spring(七)持久层
    CSS 类选择器(四)
    BeanFactory not initialized or already closed
    Spring(六)AOP切入方式
    Postman Mock Server
    Sentry快速开始并集成钉钉群机器人
    OAuth2实现单点登录SSO
    图解TCP三次握手
  • 原文地址:https://www.cnblogs.com/Kaysin/p/2915691.html
Copyright © 2011-2022 走看看