在Python中从DOCX文档中提取表格

5 投票
3 回答
13819 浏览
提问于 2025-04-16 23:48

我正在尝试从DOCX格式的Word文档中提取表格内容,但我对xml和xpath还很陌生。

from docx import *
document = opendocx('someFile.docx')
tableList = document.xpath('/w:tbl')

这导致了一个错误,提示“XPathEvalError: 未定义的命名空间前缀”。我知道这是在开发脚本时常见的第一个错误。不过,我找不到关于python-docx的教程。

能否请你提供一个提取表格的例子呢?

3 个回答

0

你可以使用python-docx这个工具从docx文件中提取表格。下面是一个示例代码:

from docx import Document()
document = Document(file_path)

tables = document.tables
1

首先,按照@abdulsaboor的建议安装 python-docx 这个库。

pip install python-docx

然后,下面的代码应该可以实现你的需求:

from docx import Document


document = Document('myfile.docx')

for table in document.tables:
    print()
    for row in table.rows:
        for cell in row.cells:
            print(cell.text, end=' ')
2

经过一番讨论,我们发现要让这个功能正常工作,需要用到命名空间。使用xpath方法是合适的解决方案,只需要先传入文档的命名空间。

lxml的xpath方法里有关于命名空间的详细信息。你可以在链接的页面下方找到如何传递命名空间字典和其他相关细节。

正如mgierdal在他上面的评论中解释的:

tblList = document.xpath('//w:tbl', namespaces=document.nsmap) 运行得非常顺利。所以,按照我的理解,w:是一个简写,需要扩展为完整的命名空间名称,而这个字典是通过document.nsmap提供的。

撰写回答