Python中读取.doc文件有什么好办法?注意是.doc,不是.docx

Python中读取.doc文件有什么好办法?注意是.doc,不是.docx

9 回复

找到了这个办法。
antiword 是 linux 及其他 RISC OS 下免费的 ms word 文档读取器。使用它可以很方便的在 Linux 中读取 word 文档并输出为纯文本字符串。

下载地址: http://www.winfield.demon.nl

下载后解压、编译安装:

tar -zxvf antiword-0.37.tar.gz
cd antiword-0.37
make
make install
默认安装到当前账户下的 bin 目录中。

使用:
终端中

/home/pi/bin/antiword antiword-test.doc
其他语言中通过各自执行系统命令的方式来执行,比如 Python 中:

import subprocess
word_file = “antiword-test.doc"
content = subprocess.check_output([”/home/pi/antiword", word_file])
print content


用python-doc处理.doc文件最直接,但需要配合反编译工具。

import subprocess
import sys
import os

def doc_to_text(doc_path):
    """
    将.doc文件转换为文本
    依赖:antiword(Linux/macOS)或catdoc(跨平台)
    """
    # 检查文件是否存在
    if not os.path.exists(doc_path):
        raise FileNotFoundError(f"文件不存在: {doc_path}")
    
    # 尝试使用antiword(Linux/macOS常见)
    try:
        result = subprocess.run(
            ['antiword', doc_path],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout
    except (subprocess.CalledProcessError, FileNotFoundError):
        pass
    
    # 尝试使用catdoc(跨平台方案)
    try:
        result = subprocess.run(
            ['catdoc', doc_path],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout
    except (subprocess.CalledProcessError, FileNotFoundError):
        pass
    
    # 备用方案:使用python-doc(纯Python,但功能有限)
    try:
        import doc
        with open(doc_path, 'rb') as f:
            doc_text = doc.Document(f.read())
            return doc_text.summary()
    except ImportError:
        raise ImportError("请安装必要的依赖:antiword/catdoc 或 python-doc")

# 使用示例
if __name__ == "__main__":
    text_content = doc_to_text("example.doc")
    print(text_content[:500])  # 打印前500字符

安装依赖:

# Ubuntu/Debian
sudo apt-get install antiword catdoc

# macOS
brew install antiword catdoc

# Python包
pip install python-doc

说明:

  1. antiword/catdoc:外部工具,转换效果最好,但需要系统安装
  2. python-doc:纯Python库,但解析能力有限,适合简单文档
  3. 如果文档包含复杂格式(表格、图片),可能需要先用libreoffice --headless --convert-to txt转换

一句话建议: 优先用antiword/catdoc,需要纯Python方案再考虑python-doc。

但是这个办法是 Linux 下的有没有 win 下的办法那?

先用 win32com 把 doc 转换成 docx,然后再用 python-docx 读 docx 就比较好处理了

这个办法我试过了,doc 转 docx 的时候电脑会打开 doc 文件,好像我这盗版的有啥文件缺失,没法转成功

找台电脑转 docx

我非常确定 Antiword 支持 Windows,我在 Windows 下用它来实现 Word 文档的 git diff。

确定能这样用?

回到顶部