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()
        
相关推荐
oyguyteggytrrwwwrt17 分钟前
3dgs渲染部分详细注释
python
松仔log24 分钟前
Java中级——组合和继承
android·java·开发语言
天天爱吃肉82182 小时前
【重磅发布:拿下新超仁达代理权 】
大数据·人工智能·python·功能测试·汽车
(Charon)2 小时前
【C++】锁与原子操作(四):自旋锁的完整实现与性能优化
c语言·开发语言·c++
神王宝宝 王者小学2 小时前
面向领域驱动架构的查询实现方式
前端·python·架构
雨田言炎2 小时前
五、Qt控件使用说明大全
开发语言·qt
bu_shuo3 小时前
MATLAB中的meshgrid和ndgrid
开发语言·matlab
ningmengjing_3 小时前
Redis 从入门到实战:Python操作全攻略
数据库·redis·python
️学习的小王3 小时前
智能文档助手:基于RAG的本地化文档问答系统实战指南
人工智能·python·机器学习
我命由我123454 小时前
Jetpack Compose - MaterialExpressiveTheme 与 MaterialTheme、ColorScheme
android·java·开发语言·java-ee·kotlin·android jetpack·android runtime