拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Python办公12:搜索文件夹内数千个文档中的特定关键字

12内容检索——搜索文件夹内数千个文档中的特定关键字第二阶段文件管理与系统自动化9-15场景引入领导问你“去年 3 月份关于华为项目的合同在哪里”你面对 50 个文件夹、3000 多个文档用 Windows 自带的搜索只能搜文件名搜不到文件内容。逐份打开文件 CtrlF 查找太慢了。本节教你用 Python 实现全文内容搜索3000 份文档只需几秒钟。技术原理核心流程遍历文件夹 → 识别文件类型 → 读取文本内容 → 正则/字符串匹配关键词 → 输出匹配结果支持的文件类型文件类型读取方式依赖库.txt, .csv, .md, .py直接open().read()内置.docxpython-docx需安装.pdfPyPDF2/pdfplumber需安装.xlsxpandas/openpyxl需安装环境准备pipinstallpython-docx PyPDF2 openpyxl完整代码importosimportrefrompathlibimportPathfromdatetimeimportdatetime# 文本提取器 defextract_text_txt(file_path):读取纯文本文件encodings[utf-8,gbk,gb2312,latin-1]forencinencodings:try:withopen(file_path,r,encodingenc)asf:returnf.read()exceptUnicodeDecodeError:continuereturndefextract_text_docx(file_path):读取 Word 文档try:fromdocximportDocument docDocument(str(file_path))return\n.join([p.textforpindoc.paragraphs])exceptException:returndefextract_text_pdf(file_path):读取 PDF 文档try:importPyPDF2 textwithopen(str(file_path),rb)asf:readerPyPDF2.PdfReader(f)forpageinreader.pages:page_textpage.extract_text()ifpage_text:textpage_text\nreturntextexceptException:returndefextract_text_xlsx(file_path):读取 Excel 文件的所有单元格文本try:importpandasaspd dfpd.read_excel(file_path,engineopenpyxl)returndf.to_string()exceptException:return# 提取器映射EXTRACTORS{.txt:extract_text_txt,.csv:extract_text_txt,.md:extract_text_txt,.py:extract_text_txt,.log:extract_text_txt,.ini:extract_text_txt,.json:extract_text_txt,.docx:extract_text_docx,.pdf:extract_text_pdf,.xlsx:extract_text_xlsx,.xls:extract_text_xlsx,}# 核心搜索函数 defsearch_files_content(search_dir,keywords,file_typesNone,max_results50,case_sensitiveFalse): 在文件夹中搜索包含特定关键字的文件 参数: search_dir: 搜索目录 keywords: 搜索关键字字符串或列表 file_types: 文件后缀过滤如 [.docx, .pdf]None 表示全部 max_results: 最多返回结果数 case_sensitive: 是否区分大小写 ifisinstance(keywords,str):keywords[keywords]search_pathPath(search_dir)results[]files_searched0print(f开始搜索:{search_dir})print(f关键字:{, .join(keywords)})print(-*50)forfile_pathinsearch_path.rglob(*):iffile_path.is_file():suffixfile_path.suffix.lower()# 文件类型过滤iffile_typesandsuffixnotinfile_types:continue# 获取提取器extractorEXTRACTORS.get(suffix)ifnotextractor:continuefiles_searched1try:contentextractor(file_path)ifnotcontent:continue# 搜索关键字matched_keywords[]search_contentcontentifcase_sensitiveelsecontent.lower()forkwinkeywords:search_kwkwifcase_sensitiveelsekw.lower()ifsearch_kwinsearch_content:matched_keywords.append(kw)ifmatched_keywords:# 提取关键字周围的上下文contextextract_context(content,keywords,case_sensitive)results.append({file:str(file_path),matched:matched_keywords,context:context,size:file_path.stat().st_size,modified:datetime.fromtimestamp(file_path.stat().st_mtime)})print(f[匹配]{file_path.name})print(f 关键字:{, .join(matched_keywords)})print(f 上下文: ...{context}...)print()iflen(results)max_results:breakexceptExceptionase:pass# 跳过无法读取的文件# 汇总报告print(*50)print(f搜索完成!)print(f扫描文件:{files_searched})print(f匹配文件:{len(results)})# 导出报告ifresults:importpandasaspd reportpd.DataFrame(results)report_file搜索结果报告.xlsxreport.to_excel(report_file,indexFalse,engineopenpyxl)print(f详细报告已导出:{report_file})returnresultsdefextract_context(text,keywords,case_sensitive,context_length50):提取关键字周围的上下文文本search_texttextifcase_sensitiveelsetext.lower()forkwinkeywords:search_kwkwifcase_sensitiveelsekw.lower()possearch_text.find(search_kw)ifpos0:startmax(0,pos-context_length)endmin(len(text),poslen(kw)context_length)returntext[start:end].replace(\n, )return# 使用示例 if__name____main__:# 示例 1搜索单个关键字 resultssearch_files_content(search_dirrD:\工作文档,keywords华为,file_types[.docx,.pdf,.xlsx])# 示例 2搜索多个关键字 # results search_files_content(# search_dirrD:\工作文档,# keywords[合同, 华为, 2024],# max_results20# )# 示例 3正则表达式搜索 # 需要自定义扩展在提取内容后用 re.search 匹配代码逐行解析1. 多编码兼容encodings[utf-8,gbk,gb2312,latin-1]forencinencodings:try:withopen(file_path,r,encodingenc)asf:returnf.read()exceptUnicodeDecodeError:continueWindows 中文环境下文本文件可能使用 GBK 编码。依次尝试多种编码确保能正确读取中文内容。2. 提取器映射EXTRACTORS{.txt:extract_text_txt,.docx:extract_text_docx,.pdf:extract_text_pdf,...}通过字典映射根据文件后缀自动选择对应的文本提取函数扩展性极强。添加新类型只需增加一行映射。3. 上下文提取defextract_context(text,keywords,context_length50):possearch_text.find(search_kw)startmax(0,pos-context_length)endmin(len(text),poslen(kw)context_length)returntext[start:end]在搜索结果中显示关键字前后 50 个字符的上下文方便快速判断是否为目标文件。进阶技巧技巧 1使用正则表达式搜索importredefsearch_with_regex(search_dir,pattern):使用正则表达式搜索regexre.compile(pattern,re.IGNORECASE)forfile_pathinPath(search_dir).rglob(*):iffile_path.is_file()andfile_path.suffix.txt:contentfile_path.read_text(encodingutf-8,errorsignore)matchesregex.findall(content)ifmatches:print(f{file_path}:{matches})技巧 2全文索引加速适合频繁搜索如果经常搜索同一批文件可以先建立索引importsqlite3defbuild_index(search_dir,db_filefile_index.db):connsqlite3.connect(db_file)conn.execute(CREATE TABLE IF NOT EXISTS files (path TEXT, content TEXT, modified REAL))forfile_pathinPath(search_dir).rglob(*):iffile_path.is_file():contentextract_text(file_path)conn.execute(INSERT OR REPLACE INTO files VALUES (?, ?, ?),(str(file_path),content,file_path.stat().st_mtime))conn.commit()conn.close()然后用 SQL 查询resultsconn.execute(SELECT path FROM files WHERE content LIKE %华为%)常见问题Q1PDF 搜索不到内容有些 PDF 是扫描件图片格式PyPDF2无法提取文本。需要使用 OCRpipinstallpdfplumber pytesseract pillowQ2搜索速度太慢使用file_types参数缩小搜索范围排除不需要搜索的大文件如日志文件可能很大对于频繁搜索的场景建立索引技巧 2Q3搜索结果太多怎么看导出为 Excel 报告后可以按文件大小、修改时间排序或在 Excel 中筛选。总结步骤方法说明识别类型file_path.suffix获取文件扩展名提取文本多提取器字典按类型选择提取方法匹配关键字kw in content字符串包含判断提取上下文extract_context()显示关键字周围文本导出报告pd.DataFrame().to_excel()Excel 格式结果本节掌握了全文内容搜索的能力再也不怕找不到文件的问题。下一节预告13空间清理——自动识别并删除电脑中的重复文件与大内存垃圾
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门