document_parser.py 6.08 KB
import os

def extract_text_from_file(file_path: str) -> str:
    """
    根据文件后缀提取文档中的纯文本内容。
    支持的格式: .txt, .md, .json, .pdf, .docx, .pptx, .xlsx, .xls
    如果遇到不支持的格式,将尝试作为纯文本读取。
    """
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"未找到文件,请检查路径是否正确: {file_path}")

    # 获取文件后缀名并统一转换为小写,以进行格式路由
    ext = os.path.splitext(file_path)[1].lower()

    try:
        # 基于常见文本格式进行路由
        if ext in ['.txt', '.md', '.json', '.xml', '.csv']:
            return _extract_text_plain(file_path)
        # 路由到 PDF 解析器
        elif ext == '.pdf':
            return _extract_text_pdf(file_path)
        # 路由到 Word 文档解析器
        elif ext == '.docx':
            return _extract_text_docx(file_path)
        # 路由到 PPT 演示文稿解析器
        elif ext == '.pptx':
            return _extract_text_pptx(file_path)
        # 路由到 Excel 表格解析器
        elif ext in ['.xlsx', '.xls']:
            return _extract_text_excel(file_path)
        else:
            # 对于未明确支持的文件后缀(例如 .log, .conf 等),
            # 默认作为纯文本文件尝试读取,充当降级(Fallback)方案
            return _extract_text_plain(file_path)
    except Exception as e:
        # 将底层解析错误包装为 RuntimeError 向上抛出,方便上层捕获和记录
        raise RuntimeError(f"从文件 {file_path} 提取文本时发生错误: {str(e)}")

def _extract_text_plain(file_path: str) -> str:
    """
    读取纯文本文件的内容,内置自动探测编码机制。
    
    参数:
        file_path (str): 文本文件路径
        
    返回:
        str: 文本文件内容
    """
    # 尝试使用多种常见编码顺序读取,以兼容不同来源的文本文件(特别是 Windows 默认的 gbk)
    for enc in ['utf-8', 'gbk', 'latin-1']:
        try:
            with open(file_path, 'r', encoding=enc) as f:
                return f.read()
        except UnicodeDecodeError:
            # 如果当前编码解码失败,静默捕获并尝试列表中的下一种编码
            continue
            
    # 如果所有常见编码都失败,最后作为兜底方案(Fallback)
    # 强制使用 utf-8 读取,并且遇到无法解码的字符时使用 'replace'(替换为 ),防止程序直接崩溃
    with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
        return f.read()

def _extract_text_pdf(file_path: str) -> str:
    """
    解析 PDF 文档并提取每一页的文本。
    
    参数:
        file_path (str): PDF 文件路径
        
    返回:
        str: 合并后的 PDF 文本内容
    """
    # 使用 PyMuPDF (fitz) 库,它是目前 Python 提取 PDF 文本性能和准确度较高的库
    import fitz  
    text_content = []
    
    # 使用上下文管理器打开 PDF 文件,确保资源会被正确释放
    with fitz.open(file_path) as doc:
        for page in doc:
            # 获取单页的全部文本,并追加到结果列表中
            text_content.append(page.get_text())
            
    # 使用双换行符连接所有页面的文本,使得段落间有合理的空白间隔
    return "\n\n".join(text_content)

def _extract_text_docx(file_path: str) -> str:
    """
    解析 Word (.docx) 文档,提取所有段落以及表格内的文本。
    
    参数:
        file_path (str): Word 文件路径
        
    返回:
        str: 拼接好的 Word 文本和表格内容
    """
    import docx
    doc = docx.Document(file_path)
    text_content = []
    
    # 1. 遍历文档中的所有常规段落
    for para in doc.paragraphs:
        if para.text.strip():
            text_content.append(para.text)
            
    # 2. 遍历文档中所有的表格,将表格数据扁平化提取
    for table in doc.tables:
        for row in table.rows:
            # 将同一行内的各个单元格文本通过 ' | ' 拼接,模拟 Markdown 表格格式
            row_data = [cell.text.strip() for cell in row.cells if cell.text.strip()]
            if row_data:
                text_content.append(" | ".join(row_data))
                
    # 使用单换行符连接所有段落和表格行
    return "\n".join(text_content)

def _extract_text_pptx(file_path: str) -> str:
    """
    解析 PPT (.pptx) 演示文稿,遍历幻灯片中的文本框。
    
    参数:
        file_path (str): PPT 文件路径
        
    返回:
        str: 提取到的演示文稿纯文本
    """
    import pptx
    prs = pptx.Presentation(file_path)
    text_content = []
    
    # 遍历所有幻灯片页面
    for slide in prs.slides:
        # 遍历单页幻灯片上的所有形状(Shapes)
        for shape in slide.shapes:
            # 检查形状是否包含文本属性,并确保文本非空
            if hasattr(shape, "text") and shape.text.strip():
                text_content.append(shape.text)
                
    return "\n\n".join(text_content)

def _extract_text_excel(file_path: str) -> str:
    """
    解析 Excel 表格 (.xlsx, .xls) 数据。
    利用 Pandas 框架一次性读取所有 Sheet,并转化为纯文本表现形式。
    
    参数:
        file_path (str): Excel 文件路径
        
    返回:
        str: 包含所有 Sheet 数据的纯文本格式
    """
    import pandas as pd
    text_content = []
    
    # sheet_name=None 表示读取工作簿中的所有工作表 (Sheets),返回结果为一个字典
    # 键为 Sheet 名称,值为对应的 DataFrame 对象
    df_dict = pd.read_excel(file_path, sheet_name=None)
    
    for sheet_name, df in df_dict.items():
        # 添加 Sheet 标题作为明显的分隔符
        text_content.append(f"--- Sheet: {sheet_name} ---")
        
        # 将 DataFrame 转换为字符串格式
        # index=False 意味着不输出行号索引,使结果更接近纯数据表格
        text_content.append(df.to_string(index=False))
        
    return "\n\n".join(text_content)