我是python的新手。我想从docx文件中提取非结构化数据作为键值对。数据采用表格格式和原始文本格式。我以前曾从表中提取过值,但是我不知道该怎么做。有人可以告诉我我指的是哪个包装或链接以对此有所了解吗?
答案 0 :(得分:3)
安装python-docx
pip install python-docx
并尝试以下代码
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")