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()
        
相关推荐
chilavert3182 分钟前
技术演进中的开发沉思-328 JVM:垃圾回收(上)
java·开发语言·jvm
qq_397562313 分钟前
Qt_工程执行逻辑_窗口逻辑
开发语言·qt
hoiii1875 分钟前
基于MATLAB的Kriging代理模型实现与优化
开发语言·matlab
火云洞红孩儿5 分钟前
2026年,用PyMe可视化编程重塑Python学习
开发语言·python·学习
2401_841495646 分钟前
【LeetCode刷题】两两交换链表中的节点
数据结构·python·算法·leetcode·链表·指针·迭代法
幻云20107 分钟前
Next.js 之道:从入门到精通
前端·javascript·vue.js·人工智能·python
SunnyDays101110 分钟前
使用 Python 自动查找并高亮 Word 文档中的文本
经验分享·python·高亮word文字·查找word文档中的文字
2501_9445215912 分钟前
Flutter for OpenHarmony 微动漫App实战:标签筛选功能实现
android·开发语言·前端·javascript·flutter
深蓝电商API15 分钟前
Selenium处理弹窗、警报和验证码识别
爬虫·python·selenium
深蓝电商API20 分钟前
Selenium模拟滚动加载无限下拉页面
爬虫·python·selenium