python-docx从段落中获取表格

时间:2015-03-24 18:57:22

标签: python document docx paragraphs

我的.docx文件包含许多段落和表格,如:

  1. PAR1
    • 表1
    • 表2
    • 表3
  2. PAR2

    • 表1
    • 表2

    2.1 par21

    • 表1
    • 表2
  3. 我需要迭代所有对象并制作字典,可能是json格式,如:

       {par1: [table1, table2, table3], par2[table1,table2, {par21: [table1,table2]} ] }
    
        from docx.api import Document
    
        filename = 'test.docx'
        document = Document(docx=filename)
        for table in document.tables:
            print table
    
        for paragraph in document.paragraphs:
            print paragraph.text
    

    我如何关联每个段落和表格?

    你能提出一些建议吗?

3 个答案:

答案 0 :(得分:2)

from docx import Document
from docx.document import Document as _Document
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
def iter_block_items(parent):
"""
Generate a reference to each paragraph and table child within *parent*,
in document order. Each returned value is an instance of either Table or
Paragraph. *parent* would most commonly be a reference to a main
Document object, but also works for a _Cell object, which itself can
contain paragraphs and tables.
"""
if isinstance(parent, _Document):
    parent_elm = parent.element.body
elif isinstance(parent, _Cell):
    parent_elm = parent._tc
elif isinstance(parent, _Row):
    parent_elm = parent._tr
else:
    raise ValueError("something's not right")
for child in parent_elm.iterchildren():
    if isinstance(child, CT_P):
        yield Paragraph(child, parent)
    elif isinstance(child, CT_Tbl):
        yield Table(child, parent)
document = Document('test.docx')
for block in iter_block_items(document):

#print(block.text if isinstance(block, Paragraph) else '<table>')
if isinstance(block, Paragraph):
    print(block.text)
elif isinstance(block, Table):
    for row in block.rows:
        row_data = []
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                row_data.append(paragraph.text)
        print("\t".join(row_data))

答案 1 :(得分:1)

在python-docx库上还没有实现这样的方法,但是有一种解决方法可以按照它们的呈现顺序遍历docx的所有元素:https://github.com/python-openxml/python-docx/issues/40

您可以尝试迭代所有这些并检查对象是否是表或段落的实例,并将逻辑基于此。

答案 2 :(得分:0)

不确定我是否在帮忙,但这是我的工作方式

def printTables(doc):
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    print(paragraph.text)
                printTables(cell)