You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python读取文件夹中PDF与Word文件并生成两列表格

基于Python提取文件夹内PDF/Word内容并生成表格的实现方案

1. 安装依赖库

首先安装处理不同文件类型的必备库:

  • 处理PDF:PyPDF2
  • 处理docx:python-docx
  • 处理doc(Windows环境):pywin32

执行安装命令:

pip install PyPDF2 python-docx pywin32

2. 核心代码实现

以下代码会遍历指定文件夹,自动识别PDF、doc、docx文件并提取文本,最终生成包含文件ID和文本内容的结构化表格(支持直接打印或导出为CSV):

import os
from PyPDF2 import PdfReader
from docx import Document
import win32com.client as win32

def extract_pdf_text(file_path):
    """提取PDF文件文本内容"""
    text = ""
    try:
        reader = PdfReader(file_path)
        for page in reader.pages:
            extracted = page.extract_text()
            if extracted:
                text += extracted
    except Exception as e:
        print(f"处理PDF [{file_path}] 出错: {str(e)}")
    return text.strip()

def extract_docx_text(file_path):
    """提取docx文件文本内容"""
    text = ""
    try:
        doc = Document(file_path)
        for para in doc.paragraphs:
            text += para.text + "\n"
    except Exception as e:
        print(f"处理docx [{file_path}] 出错: {str(e)}")
    return text.strip()

def extract_doc_text(file_path):
    """提取doc文件文本内容(仅Windows环境,依赖本地Word)"""
    text = ""
    try:
        word_app = win32.gencache.EnsureDispatch("Word.Application")
        word_app.Visible = False
        doc = word_app.Documents.Open(os.path.abspath(file_path))
        text = doc.Content.Text
        doc.Close()
        word_app.Quit()
    except Exception as e:
        print(f"处理doc [{file_path}] 出错: {str(e)}")
    return text.strip()

def process_target_folder(folder_path):
    """遍历文件夹,处理所有目标文件并生成表格"""
    result_table = []
    current_id = 1
    for filename in os.listdir(folder_path):
        full_path = os.path.join(folder_path, filename)
        if not os.path.isfile(full_path):
            continue
        
        # 根据文件后缀调用对应提取函数
        if filename.lower().endswith(".pdf"):
            content = extract_pdf_text(full_path)
        elif filename.lower().endswith(".docx"):
            content = extract_docx_text(full_path)
        elif filename.lower().endswith(".doc"):
            content = extract_doc_text(full_path)
        else:
            continue
        
        result_table.append({
            "文件ID": current_id,
            "文本内容": content
        })
        current_id += 1
    return result_table

if __name__ == "__main__":
    # 替换为你的目标文件夹路径
    target_dir = r"C:\Your\Target\Folder"
    file_content_table = process_target_folder(target_dir)
    
    # 打印结果示例
    for item in file_content_table:
        print(f"文件ID: {item['文件ID']}")
        print(f"文本内容:\n{item['文本内容']}\n{'='*60}")
    
    # 可选:导出为CSV文件(解决中文乱码问题)
    import csv
    with open("文件内容汇总表.csv", "w", encoding="utf-8-sig", newline="") as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=["文件ID", "文本内容"])
        writer.writeheader()
        writer.writerows(file_content_table)

3. 注意事项

  • doc文件兼容性:pywin32仅支持Windows环境,依赖本地安装的Microsoft Word;Linux/macOS环境可尝试使用antiword工具配合subprocess调用,或安装textract库(需额外配置系统依赖)。
  • 特殊PDF处理:扫描版PDF无法直接提取文本,需搭配OCR工具(如pytesseract)预处理;加密PDF需先解密才能读取。
  • 编码问题:导出CSV时使用utf-8-sig编码,可避免Excel打开时出现中文乱码。

内容的提问来源于stack exchange,提问作者Hugo Coras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:30:24