'python-docx get tables from paragraph
I have .docx file with many paragraphs and tables like:
- par1
- table1
- table2
- table3
par2
- table1
- table2
2.1 par21
- table1
- table2
I need to iterate all objects and make dictionary, maybe in json format like:
{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
How can I relate each paragraph and tables?
Can you suggest something ?
Solution 1:[1]
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))
Solution 2:[2]
Not sure if i am helping but here's my way of doing
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)
Solution 3:[3]
There is no such method implemented(yet) on the python-docx library but there is a workaround to iterate through all elements of the docx in the order they are presented: https://github.com/python-openxml/python-docx/issues/40
You can try iterating through all these and check if the object is an instance of a table or paragraph and base your logic on that.
Solution 4:[4]
This functions returns the paragraphs and tables of a document or part of a document (you can have paragraphs and tables inside tables):
def iter_block_items(parent):
# https://github.com/python-openxml/python-docx/issues/40
from docx.document import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
"""
Yield 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
else:
raise ValueError("something's not right")
# print('parent_elm: '+str(type(parent_elm)))
for child in parent_elm.iterchildren():
if isinstance(child, CT_P):
yield Paragraph(child, parent)
elif isinstance(child, CT_Tbl):
yield Table(child, parent) # No recursion, return tables as tables
# table = Table(child, parent) # Use recursion to return tables as paragraphs
# for row in table.rows:
# for cell in row.cells:
# yield from iter_block_items(cell)
Now, to use it, construct your dictionary where it says Do some logic here
:
document = Document(filepath)
for iter_block_item in iter_block_items(document): # Iterate over paragraphs and tables
# print('iter_block_item type: '+str(type(iter_block_item)))
if isinstance(iter_block_item, Paragraph):
paragraph = iter_block_item # Do some logic here
else:
table = iter_block_item # Do some logic here
Note: @Elayaraja Dev answer cannot be edited, this answer has the current form of iter_block_items (since docx internals were updated)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | insolor |
Solution 2 | |
Solution 3 | grafuls |
Solution 4 | Zeta |