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()
        
相关推荐
何以解忧,唯有..14 分钟前
Pydantic 介绍与使用:Python 数据校验的现代方案
数据库·python·microsoft
kyle~26 分钟前
C++_STL---迭代器失效
开发语言·c++
又幸福了哥1 小时前
Python入门到高级(知识点七)
python
Brilliantwxx1 小时前
【C语言】 初入嵌入式C语言复习(基础+进阶面试题)
c语言·开发语言
熊野君2 小时前
附录与 Codex 实操手册
开发语言·人工智能·产品经理
又幸福了哥2 小时前
Python入门到高级(知识点六)
python
维克兜率天2 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
XZ-0700013 小时前
week2-1-可视化
开发语言·python
Java后端的Ai之路3 小时前
14、Python - 责任链模式
服务器·开发语言·人工智能·python·责任链模式
张人玉3 小时前
基于 Python 机器学习 与 PyQt5 桌面框架开发的可视化分析系统——基于大数据的网上购物消费行为分析可视化大屏
python·qt·机器学习·echarts·three.js