有没有一种合理的方法可以从Word文件中提取纯文本,而不依赖于COM自动化?(这是部署在非Windows平台上的web应用程序的一个功能-在这种情况下,这是没有商量余地的。)
Antiword似乎是一个合理的选择,但它似乎可能会被放弃。
Python解决方案将是理想的,但似乎不可用。
发布于 2008-09-04 08:52:01
我使用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()
-w切换到catdoc会关闭换行。
发布于 2009-12-30 20:23:05
(答案与extracting text from MS word files in python相同)
使用我本周制作的原生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。
发布于 2013-12-19 00:38:12
如果您只想从Word文件(.docx)中提取文本,那么只使用Python语言也是可行的。就像Guy Starbuck写的一样,你只需要解压缩文件,然后解析XML。受python-docx
的启发,我写了一个simple function来做这件事:
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)
https://stackoverflow.com/questions/42482
复制相似问题