用python从DOCX Word文档中提取表

2024-06-02 00:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在DOCX Word文档中提取表的内容,而且我对xml/xpath还不熟悉。

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

这会触发“xpathevaleror:Undefined namespace prefix”错误。我相信这只是开发脚本时的第一个期望。不幸的是,我找不到python-docx的教程。

你能提供一个表格提取的例子吗?


Tags: from文档import内容xmldocumentxpathsomefile
2条回答

可以使用python docx从docx中提取表。检查以下代码:

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

tables = document.tables

经过一番反复,我们发现需要一个名称空间才能正常工作。xpath方法是合适的解决方案,它只需要首先传递文档命名空间。

lxml xpath method包含命名空间内容的详细信息。查看链接中的页面以获取传递名称空间字典和其他详细信息的信息。

正如mgierdal在其上述评论中所解释的:

tblList = document.xpath('//w:tbl', namespaces=document.nsmap) works like a dream. So, as I understand it w: is a shorthand that has to be expanded to the full namespace name, and the dictionary for that is provided by document.nsmap.

相关问题 更多 >