-1

I am new to python I have few doc files in that the paragraph and tables are jumbled in some random order and I want to read those in the exact order and print those

For example: Input file containing data in the below order


  1. Paragraph
  2. Table
  3. Paragraph
  4. Paragraph
  5. Table
  6. Paragraph
  7. Table

I used he below code for this:-

for para in document.paragraphs:
    print(para.text)

for table in document.tables:
    for row in table.rows:
        for cell in row.cells:
            print(cell.text)

The output I got is it printed all text paragraphs together and then it printed all text in tables together. But I want the output as if in the given order in the document.

vikash vishnu
  • 337
  • 1
  • 4
  • 11

1 Answers1

1

Hope the below answer will be a correct solution

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
        # print(parent_elm.xml)
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    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)

"""
Reading the document.
"""
document = Document(r"D:\Vikash\Tool_Python\ragavi_dog.docx")
for block in iter_block_items(document):
    print('found one instance')
    if isinstance(block, Paragraph):
        print("paragraph")
        #write the code here
    else:
        print("table")
        #write the code here
vikash vishnu
  • 337
  • 1
  • 4
  • 11