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()
        
相关推荐
sugar__salt2 分钟前
从Python列表切片到LLM接口实战:零基础AI编程落地教程
开发语言·python·ai·prompt·transformer·ai编程
乐于分享的阿乐4 分钟前
Miniconda3 超详细安装配置教程(附安装包及学习资料)
python
z落落7 分钟前
C# 数组属性和方法(Clear / Copy / IndexOf / LastIndexOf)
开发语言·javascript·c#
白露与泡影9 分钟前
Java虚拟线程实战:从线程池痛点到性能优化全流程
java·开发语言·性能优化
IT空门:门主13 分钟前
Java 单例模式详解:7 种实现方式 + volatile 原理 + 反射与序列化问题
java·开发语言·单例模式
gis分享者13 分钟前
从原理到落地,Python 实现客户细分与销量预测
python·客户细分,销量预测,商业智能
Byte Wizard16 分钟前
自定义类型:联合和枚举
c语言·开发语言
Zhang~Ling24 分钟前
C++ 继承机制详解下:多继承、虚继承与菱形继承底层原理
开发语言·c++·算法
思麟呀26 分钟前
C++工业级日志项目(四)日志落地
linux·开发语言·c++·windows