python-docx顺序读取word内容

来源How to use Python iteration to read paragraphs, tables and pictures in word? · Issue #650 · python-openxml/python-docx (github.com)

python 复制代码
from docx import Document
from docx.oxml.ns import qn

def iter_block_items(parent):
    """
    生成 `parent` 元素的每个块级元素,包括段落和表格。
    """
    parent_elm = parent.element.body

    for child in parent_elm.iterchildren():
        if child.tag == qn('w:p'):
            yield 'p', child
        elif child.tag == qn('w:tbl'):
            yield 'tbl', child

# 打开文档
doc = Document("example.docx")

paragraphs = doc.paragraphs
tables = doc.tables

paragraph_index = 0
table_index = 0

for block_type, block in iter_block_items(doc):
    if block_type == 'p':
        paragraph = paragraphs[paragraph_index]
        print("Paragraph:", paragraph.text)
        paragraph_index += 1
    elif block_type == 'tbl':
        table = tables[table_index]
        table_index += 1
        if table:
            print("Table:")
            for n_r, row in enumerate(table.rows):
                print(f"    Row {n_r}: ")
                for n_c, cell in enumerate(row.cells):
                    print(f"        Column {n_c}:", cell.text, end=' ')
                print()
        
相关推荐
一壶浊酒..2 小时前
Scrape Webpack练习
开发语言·javascript·webpack
命运之光2 小时前
【C语言完整代码】就诊信息管理系统
java·c语言·开发语言
命运之光2 小时前
【C语言完整代码】图书管理系统:图书馆场景下的增删改查实战
c语言·开发语言
猿长大人3 小时前
C# | Serilog 新手入门
开发语言·c#·.net·log
今儿敲了吗4 小时前
Python ——第三方包
笔记·python
麒麟水手4 小时前
国产银河麒麟系统开发实录:跑通Streamlit,我踩过的6个坑
python
麒麟水手4 小时前
麒麟系统部署检查清单:上线前30分钟,逐项自查这4类问题
python
在世修行4 小时前
从零打造 C# 工业视觉检测系统(七):串口通信 SerialPort 封装与开发
开发语言·c#·modbus rtu·rs232/rs485
Hammer_Hans5 小时前
DFT笔记98
java·开发语言·数据库
用户0332126663675 小时前
使用 Python 在 PDF 中添加或删除数字签名
python