在不使用 COM/自动化的情况下从 Word 文档中提取文本的最佳方法?
题
有没有一种合理的方法可以从不依赖于 COM 自动化的 Word 文件中提取纯文本?(这是部署在非 Windows 平台上的 Web 应用程序的一项功能 - 在这种情况下这是不可协商的。)
Antiword 似乎是一个合理的选择,但似乎可能会被放弃。
Python 解决方案是理想的,但似乎不可用。
解决方案
我为此使用 catdoc 或 antiword,无论给出的结果是最容易解析的。我已将其嵌入到 python 函数中,因此很容易从解析系统(用 python 编写)使用它。
import os
def doc_to_text_catdoc(filename):
(fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename)
fi.close()
retval = fo.read()
erroroutput = fe.read()
fo.close()
fe.close()
if not erroroutput:
return retval
else:
raise OSError("Executing the command caused an error: %s" % erroroutput)
# similar doc_to_text_antiword()
顺便说一句,catdoc 的 -w 开关会关闭换行。
其他提示
(与以下答案相同 在Python中从MS Word文件中提取文本)
使用我本周制作的原生 Python docx 模块。以下是从文档中提取所有文本的方法:
document = opendocx('Hello world.docx')
# This location is where most document content lives
docbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0]
# Extract all text
print getdocumenttext(document)
100% Python,没有 COM,没有 .net,没有 Java,没有使用正则表达式解析序列化 XML,没有废话。
如果您只想从 Word 文件 (.docx) 中提取文本,则只能使用 Python 来完成。就像 Guy Starbuck 写的那样,您只需解压缩文件,然后解析 XML。灵感来自 python-docx
, ,我写了一个 简单的功能 去做这个:
try:
from xml.etree.cElementTree import XML
except ImportError:
from xml.etree.ElementTree import XML
import zipfile
"""
Module that extract text from MS XML Word document (.docx).
(Inspired by python-docx <https://github.com/mikemaccana/python-docx>)
"""
WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'
def get_docx_text(path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(path)
xml_content = document.read('word/document.xml')
document.close()
tree = XML(xml_content)
paragraphs = []
for paragraph in tree.getiterator(PARA):
texts = [node.text
for node in paragraph.getiterator(TEXT)
if node.text]
if texts:
paragraphs.append(''.join(texts))
return '\n\n'.join(paragraphs)
使用 OpenOffice API 和 Python,以及 Andrew Pitonyak 的优秀在线宏观书籍 我设法做到了这一点。从第 7.16.4 节开始。
让它在不需要屏幕的情况下工作的另一个技巧是使用 Hidden 属性:
RO = PropertyValue('ReadOnly', 0, True, 0)
Hidden = PropertyValue('Hidden', 0, True, 0)
xDoc = desktop.loadComponentFromURL( docpath,"_blank", 0, (RO, Hidden,) )
否则,当您打开文档时,该文档会在屏幕上(可能在网络服务器控制台上)弹出。
开放式办公室有一个 应用程序编程接口
对于 docx 文件,请查看 Python 脚本 docx2txt,网址为
http://cobweb.ecn.purdue.edu/~kak/distMisc/docx2txt
用于从 docx 文档中提取纯文本。
提卡蟒蛇
Apache Tika 库的 Python 端口,根据文档,Apache tika 支持从 1500 多种文件格式中提取文本。
笔记: 它也可以与 py安装程序
使用 pip 安装:
pip install tika
样本:
#!/usr/bin/env python
from tika import parser
parsed = parser.from_file('/path/to/file')
print(parsed["metadata"]) #To get the meta data of the file
print(parsed["content"]) # To get the content of the file
官方链接 GitHub
这效果很好 对于 .doc 和 .odt。
它在命令行上调用 openoffice 将文件转换为文本,然后您可以简单地将其加载到 python 中。
(它似乎还有其他格式选项,尽管它们没有明显记录。)