关于MS Word:如何使用Python从doc / docx文件中提取数据

How do I extract data from a doc/docx file using Python

我知道那里也有类似的问题,但是我找不到能回答我的祷告的东西。 我需要的是一种从MS-Word文件访问某些数据并将其保存在XML文件中的方法。
在python-docx上阅读无济于事,因为它似乎只允许一个人写入Word文档,而不是阅读。
要准确呈现我的任务(或我选择如何执行任务的方式):我想在文档中搜索关键字或短语(文档包含表格),并从关键字/短语所在的表格中提取文本数据 找到了。
有人有什么想法吗?


docx是一个包含文档XML的zip文件。您可以打开zip,阅读文档并使用ElementTree解析数据。

这种技术的优点是您不需要安装任何额外的python库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import zipfile
import xml.etree.ElementTree

WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'
TABLE = WORD_NAMESPACE + 'tbl'
ROW = WORD_NAMESPACE + 'tr'
CELL = WORD_NAMESPACE + 'tc'

with zipfile.ZipFile('<path to docx file>') as docx:
    tree = xml.etree.ElementTree.XML(docx.read('word/document.xml'))

for table in tree.iter(TABLE):
    for row in table.iter(ROW):
        for cell in row.iter(CELL):
            print ''.join(node.text for node in cell.iter(TEXT))

请参阅我对如何使用Python读取MS-Word文件中表格内容的stackoverflow答案?有关更多详细信息和参考。


似乎pywin32可以解决问题。您可以遍历文档中的所有表以及表中的所有单元格。获取数据有点棘手(必须省略每个条目的最后两个字符),否则,它是一个十分钟的代码。
如果有人需要其他详细信息,请在评论中说明。


使用python-docx搜索文档

1
2
3
4
5
6
7
8
# Import the module
from docx import *

# Open the .docx file
document = opendocx('A document.docx')

# Search returns true if found    
search(document,'your search string')

您还具有获取文档文本的功能:

https://github.com/mikemaccana/python-docx/blob/master/docx.py#L910

1
2
3
4
5
6
# Import the module
from docx import *

# Open the .docx file
document = opendocx('A document.docx')
fullText=getdocumenttext(document)

使用https://github.com/mikemaccana/python-docx


具有图像提取功能的更简单的库。

1
pip install docx2txt

然后使用下面的代码读取docx文件。

1
2
import docx2txt
text = docx2txt.process("file.docx")