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()
        
相关推荐
qq_158895411112 小时前
Suno-API 是什么?官方 V6 模型与 Python / TypeScript 接入指南
python·ai音乐·suno api
星落梦生8 小时前
SpringAOP基础笔记(7)
java·开发语言
曹牧11 小时前
Java:“刷新雪崩”
java·开发语言
郝学胜-神的一滴11 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus12 小时前
C++ explicit 关键字工程实践
开发语言·c++
学无止境小袁同学13 小时前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴13 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
feixing_fx14 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
LK_0714 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk55514 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel