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

Python读取Word 97-2003版.doc文件时OpenOffice生成文件无法匹配字符串怎么办

问题原因

直接读取.doc后缀的二进制文件作为纯文本检索的方式本身不具备通用性:微软Word生成的Word 97-2003格式文件中,明文内容存在连续存储的片段,因此可以被直接读取匹配;但OpenOffice生成的同格式文件采用OLE2复合文档结构存储,文本内容和格式元数据混排、部分采用UTF-16等编码存储,直接读取无法拿到完整的明文内容,因此匹配失败。

解决方案

使用专门处理.doc格式的工具解析出文件的纯文本内容后再进行检索,推荐两种可行实现:

方案1:使用textract库跨平台解析

textract会自动调用底层解析工具适配不同来源的.doc文件,使用步骤如下:

  1. 安装对应平台的依赖工具:
    • Windows:下载安装antiword并添加到系统环境变量
    • Linux:执行apt install antiword
    • Mac:执行brew install antiword
  2. 安装Python依赖:pip install textract
  3. 修改代码如下:
import re
import textract

def procura_dentro_txt(file):
    # 解析doc文件获取纯文本
    text = textract.process(file, extension='doc').decode('utf-8', errors='ignore')
    for match in re.finditer(pattern, text):
        mostraResultado(match.group(), file, pattern)

方案2:Windows平台调用本地Word解析

如果是Windows环境且已经安装了微软Office,可以直接调用本地Word程序解析,不需要额外安装其他工具,代码如下:

import re
import os
import win32com.client

def procura_dentro_txt(file):
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = False
    try:
        doc = word.Documents.Open(os.path.abspath(file))
        text = doc.Content.Text
        doc.Close()
        for match in re.finditer(pattern, text):
            mostraResultado(match.group(), file, pattern)
    finally:
        word.Quit()

注意事项

不要直接把二进制格式的.doc文件当纯文本文件打开读取,该方式仅对少量特殊生成的文件有效,不具备通用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:24:04