python-docx:document.tables 中缺少表格

python-docx: tables missing from document.tables

当尝试访问下面 word 文档中的 table 时,document.tables 中缺少 table 内容之前的 tables https://www.fedramp.gov/assets/resources/templates/FedRAMP-SSP-High-Baseline-Template.docx

这是我导入文档并检查 tables 列表中的第一个 table 和文档第 1 节中相应的 table 的示例(在 table 的内容): https://puu.sh/DBm0O/86ee455e03.png

这是我正在尝试访问的 table https://puu.sh/DBm2f/4d447baa2e.png

我假设文档开头的 table 内容之前有与 table 相关的内容,但我找不到任何其他关于类似内容的帖子。

关于如何使用 python-docx 访问此 table(无需移动它)有什么建议吗?我是否直接使用底层 lxml 元素?谢谢!

我有一个使用 BeautifulSoup 而不是 python-docx 的解决方案。我这里所做的就是遍历word(.docx)文档的OOXML

from bs4 import BeautifulSoup
import zipfile

wordoc = input('Enter your file name here or name with path: ')
text1 = 'templaterevisionhistory'
document = zipfile.ZipFile(wordoc)
xml_content = document.read('word/document.xml')
document.close()
soup = BeautifulSoup(xml_content, 'xml')

more_content = soup.find_all('p')
for tag in more_content:
    if ''.join(tag.text.split()).lower() == text1:
        table = tag.find_next_sibling('w:tbl')
        table_contents = []
        for wtc in table.findChildren('w:tc'):
            cell_text = ''
            for wr in wtc.findChildren('w:r'):
                # We want to exclude striked-out text
                if not wr.findChildren('w:strike'):
                    cell_text += wr.text
            table_contents.append(cell_text)
        print(table_contents)

.docx 文档中的底层 XML 可以使用 opc-diag 检查,这是 python-docx.

的一个配套项目
opc browse FedRamp.docx document.xml

检查显示该文档中的 front-matter 包含在 <w:sdt> 元素中。 "sdt" 代表结构化文档标签。我不知道这些到底是什么,但它们可能与内容控制有关。无论如何,它们的存在有效地向 python-docx 隐藏了它们包含的任何内容。未接受的修订标记也会出现类似的行为。 python-docx 只是不够复杂,无法处理某些 .docx 文档中存在的这些 "advanced" 容器引入的复杂性。

如果您能以某种方式移除这些容器,将它们的内容恢复到 "top-level",一切都应该可以正常进行。如果您将此文件用作模板,那么使用 Word 编辑它们或什至手动编辑 XML 可能是最快的。如果它们是以这种方式不断到达您的输入,也许 pre-processing document.xml 部分的 XML 是一种可行的方法。