要在 Python 中读取.doc 文件(注意:是旧版 Word 格式,即.doc,而非.docx)并打印内容,可以使用 antiword 工具配合 Python 调用,或者使用 textract 库(它会自动依赖 antiword)。以下是两种常用方法:
方法 1:使用 textract 库(推荐,简化操作)
textract 是一个多功能文本提取库,支持.doc、.docx、.pdf 等多种格式,但需要先安装依赖工具。
步骤
- 安装依赖工具(必做):
- Windows:需要安装 antiword(用于解析.doc),下载地址:antiword for Windows,并将安装路径添加到系统环境变量 PATH 中。
- macOS:brew install antiword
- Linux:sudo apt-get install antiword
读取并打印.doc 内容:
import textract
text = textract.process("你的文件路径.doc", encoding='utf-8')
# 转换为字符串并打印
print(text.decode('utf-8'))
安装 Python 库:
pip install textract
方法 2:直接调用 antiword(更底层)
如果 textract 安装有问题,可以直接通过 Python 的 subprocess 模块调用 antiword 工具。
步骤:
- 先安装 antiword(同方法 1 的步骤 1)。
Python 代码:
import subprocess
def read_doc_file(file_path):
try:
# 调用 antiword 命令解析.doc 文件
result = subprocess.run(['antiword', file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding='utf-8')
# 输出内容
return result.stdout
except Exception as e:
return f"读取失败:{str(e)}"
# 使用示例
doc_content = read_doc_file("你的文件路径.doc")
print(doc_content)
注意事项
- .doc 是二进制格式,解析难度比.docx 大,上述方法依赖 antiword 工具,确保工具正确安装并配置环境变量。
- 如果是.docx 文件(新版 Word),推荐使用 python-docx 库(更简单,无需额外工具)。


