Python实现搜索关键字定位文件01

最近被新闻专业同学问起一个很实用的需求,大致是这样的:一个文件夹内有很多文件,怎么通过搜索关键字就可以找到内容包含关键字的word文件,同时获得关键字所在段落的内容。由于最近在学习Python,所以对这个需求很感兴趣,于是当时很快就把这个功能做出来了。



首先想到的自然是用脚本实现,新建一个kword.py文件,差不读四十几行代码将可以实现,步骤是这样的:
1.先获取文件夹里面的所有文件路径、其中用递归算法获取子文件夹内的文件路径:

def get_process_files(root_dir):
    """process all files in directory"""
    cur_dir=os.path.abspath(root_dir)
    file_list=os.listdir(cur_dir)
    process_list=[]
    for file in file_list:
        fullfile=cur_dir+"\\"+file
        if os.path.isfile(fullfile):
            process_list.append(fullfile)
        elif os.path.isdir(fullfile):
            dir_extra_list=get_process_files(fullfile)
            if len(dir_extra_list)!=0:
                for x in dir_extra_list:
                    process_list.append(x)
    return process_list

2.利用python-docx模块中的Document方法对word文件中每一段进行关键字匹配:

def search_word(filename,word):
    #打开文档
    document = Document(filename)
    # document = Document(r'C:\Users\Cheng\Desktop\kword\words\wind.docx')
    print filename
    #读取每段资料
    l = [ paragraph.text.encode('gb2312') for paragraph in document.paragraphs];
    #输出并观察结果,也可以通过其他手段处理文本即可
    for i in l:
        i=i.strip()
        # print i
        if i.find(word)!=-1:
            print filename, i

3.遍历每一个文件并进行查找:

def find_files(root_dir,word):
    process_list=get_process_files(root_dir)
    for files in process_list:
        search_word(files, word)

这里有两个参数需要我们自己输入,分别是文件目录和关键字。

#文件根目录
root_dir=sys.argv[1]
#要搜索的关键字
word=sys.argv[2]

至此,在脚本目录下运行“python kword.py 目录 关键字”命令就可以看到搜索结果,目前搜索功能比较简单,没有做大量文件测试和算法优化。
献上脚本源码:

#coding=utf-8
from docx import Document
import os,sys

def search_word(filename,word):
    #打开文档
    document = Document(filename)
    # document = Document(r'C:\Users\Cheng\Desktop\kword\words\wind.docx')
    print filename
    #读取每段资料
    l = [ paragraph.text.encode('gb2312') for paragraph in document.paragraphs];
    #输出并观察结果,也可以通过其他手段处理文本即可
    for i in l:
        i=i.strip()
        # print i
        if i.find(word)!=-1:
            print filename, i

def get_process_files(root_dir):
    """process all files in directory"""
    cur_dir=os.path.abspath(root_dir)
    file_list=os.listdir(cur_dir)
    process_list=[]
    for file in file_list:
        fullfile=cur_dir+"\\"+file
        if os.path.isfile(fullfile):
            process_list.append(fullfile)
        elif os.path.isdir(fullfile):
            dir_extra_list=get_process_files(fullfile)
            if len(dir_extra_list)!=0:
                for x in dir_extra_list:
                    process_list.append(x)
    return process_list

def find_files(root_dir,word):
    process_list=get_process_files(root_dir)
    for files in process_list:
        search_word(files, word)

if __name__=='__main__':
    #文件根目录
    root_dir=sys.argv[1]
    #要搜索的关键字
    word=sys.argv[2]
    try:
        find_files(root_dir,word)
    except:
        pass

如果你喜欢本文章,还请点个关注和喜欢,我会为大家不断地带来Python学习笔记。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,877评论 0 10
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,257评论 4 16
  • 陌上花开,可缓缓归矣 东风夜放花千树, 吹遍大地万紫千红春色无边。 春光多美妙, 何不寻芳去 陌上花开,可缓缓归矣...
    当时明月在zh阅读 1,528评论 5 13
  • 临秋末晚将下班,五部急如星火要两条普利司通大胎。拍马加鞭欲行,心里一咯噔,不对,货车刚才又犯了带速不转的毛病...
    曹侃阅读 335评论 0 0
  • 践行第14天2017.12.6 城市:宜兴 姓名:糖糖 一、[设定目标(3件帮助人的好事)]: 1.考虑同事力气小...
    爱阳光的TT阅读 278评论 0 0