不使用COM /自动化从Word文档中提取文本的最佳方法?

Kev*_*vin 24 python ms-word

有没有合理的方法从不依赖于COM自动化的Word文件中提取纯文本?(这是部署在非Windows平台上的Web应用程序的一项功能 - 在这种情况下是不可协商的.)

Antiword似乎可能是一个合理的选择,但似乎它可能会被抛弃.

Python解决方案是理想的,但似乎不可用.

mik*_*ana 20

(与从python中的MS word文件中提取文本的答案相同)

使用我本周制作的原生Python docx模块.以下是如何从doc中提取所有文本:

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)
Run Code Online (Sandbox Code Playgroud)

请参阅Python DocX站点

100%Python,没有COM,没有.net,没有Java,没有使用正则表达式解析序列化的XML,没有废话.

  • 如果只有一种方法可以在StackOverflow上提问. (17认同)
  • @mikemaccana 它也可以解析 .doc(不是 .docx)文件吗? (2认同)

cod*_*ape 13

我使用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()
Run Code Online (Sandbox Code Playgroud)

-w切换到catdoc会关闭换行,BTW.

  • 请注意,Python 3删除了popen3,请参阅https://docs.python.org/3/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3 (2认同)