简体   繁体   中英

Exracting unstructured data/text from docx using Python

I am a newbie in python. I want to extract unstructured data from docx file as key value pair. The data is in table format and raw text format. I have previously extracted values from table before, but I have no idea how to do this. Can someone tell me which package or link I refer to get insight on this?Thanks in advance.

数据提取

Install python-docx

pip install python-docx

And try below code

import docx
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


def iter_block_items(parent):
    if isinstance(parent, Document):
        parent_elm = parent.element.body
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    else:
        raise ValueError("Error in reading docx file")

    for child in parent_elm.iterchildren():
        if isinstance(child, CT_P):
            yield Paragraph(child, parent)
        elif isinstance(child, CT_Tbl):
            yield Table(child, parent)


def convert_docx_to_text(file_path):
    doc = docx.Document(file_path)
    for block in iter_block_items(doc):
        if isinstance(block, Table):  # check block is table
            keys = []
            for row in block.rows:  # each table row
                if not keys:
                    keys = [cell.text for cell in row.cells] # keys (table headers)
                    continue
                values = [cell.text for cell in row.cells] # values
                print(dict(zip(keys, values)))
        else:
            print(block.text)  # paragraph text

convert_docx_to_text(file_path="/home/karmveer/Downloads/my.docx")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM