python docx从文档中删除表

时间:2017-12-08 14:53:41

标签: python-docx

我想根据左上角单元格的内容从文档中删除一些表。

我试过了:

allTables = document.tables
for activeTable in allTables:
    if activeTable.cell(0,0).paragraphs[0].text == 'some text':
        allTables.remove(activeTable)

我希望删除单元格(0,0)中包含“some text”的所有表格,但它们仍在文档中。

进程按预期进入“allTables.remove(activeTable)”行:if语句中的indexToDelete = allTables.index(activeTable)给出表,我正在寻找。

消息是“处理完毕,退出代码为0”

2 个答案:

答案 0 :(得分:2)

听起来你的测试if activeTable...text == 'some text'对任何表都没有成功。在这种情况下,.remove()调用永远不会执行,但脚本仍会返回0的退出代码(成功)。

首先验证您的测试,可能是:

for table in document.tables:
    print("'%s'" % table.cell(0, 0).paragraphs[0].text)

并确保段落文本符合您的想法。这应该打印出类似的东西:

'some text but also some other text'
...

确定后,您可能希望测试除整个字符串以外的其他内容,可能使用.startswith()

text = table.cell(0, 0).paragraphs[0].text
if text.startswith('some text'):
    print('found one')

一旦你开始工作,你就可以继续讨论下一个问题。

答案 1 :(得分:1)

解决方案是:

allTables = document.tables

for activeTable in allTables:
    if activeTable.cell(0,0).paragraphs[0].text == 'some text':
        activeTable._element.getparent().remove(activeTable._element)

感谢scanny。