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()
        
相关推荐
爱我所爱flash16 分钟前
难道 Java 已经过时了?
java·开发语言·学习
小尤笔记17 分钟前
Python知识点背诵手册,超详细知识梳理
开发语言·python·学习·python入门·学习手册
经海路大白狗21 分钟前
开启IT世界的第一步:高考新生的暑期学习指南
前端·后端·python·学习·高考
阿胡爱编程25 分钟前
Java高级重点知识点-19-Lambda
java·开发语言
煜磊26 分钟前
将json对象转为xml进行操作属性
java·开发语言
concisedistinct1 小时前
Perl 语言开发(三):运算符和表达式
开发语言·后端·perl
寻至善1 小时前
Python深度理解系列之【排序算法——冒泡排序】
开发语言·python·排序算法
轩轩Aminent1 小时前
ananconda 和 pip傻傻分不清???
python·pip
zhangbin_2371 小时前
【Python机器学习】模型评估与改进——二分类指标
大数据·人工智能·python·学习·机器学习·分类·数据挖掘
maets9061 小时前
【Datawhale夏令营】大模型技术方向Task1打卡笔记
python·datawhale·星火大模型·ai夏令营