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()
        
相关推荐
四维迁跃13 小时前
JavaScript中Object-defineProperties批量设置属性
jvm·数据库·python
于先生吖13 小时前
家政派单小程序靠谱机构
python
Fleshy数模13 小时前
本地部署 Qwen2.5-1.5B-Instruct 全流程教程|Ollama + 魔搭双方案
python·语言模型·大模型·本地部署
Brilliantwxx13 小时前
【C++】认识标准库STL(2)
开发语言·c++
2501_9012005313 小时前
CSS如何让响应式字体在断点处平滑切换_使用clamp函数计算
jvm·数据库·python
毕胜客源码13 小时前
卷积神经网络的手势识别系统(有技术文档)深度学习 图像识别 卷积神经网络 Django python 人工智能
人工智能·python·深度学习·cnn·django
故事还在继续吗13 小时前
STL 容器算法手册
开发语言·c++·算法
dFObBIMmai13 小时前
如何应对高级SQL注入_配置数据库审计实时监控流量
jvm·数据库·python
techdashen14 小时前
Cloudflare 用 Rust 实现 QUIC 协议:quiche 是怎么设计的
开发语言·后端·rust