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()
        
相关推荐
jimy14 分钟前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743877 分钟前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php
happylifetree15 分钟前
Python14:核心语法-数据存储与运算-字符串定义
python
hhb_61818 分钟前
AIRAGDebug:一键定位RAG链路异常
人工智能·python·算法
朝朝辞暮i35 分钟前
C++ 第 6 课:switch —— 多状态选择
开发语言·c++·算法
小静AI工程实验室39 分钟前
asyncio.Queue 有界队列实战:背压、task_done、join 与异常收尾
python
小凡geo43 分钟前
本地商家 GEO:用脚本一键生成 FAQPage 结构化数据,让 AI 切片更稳
开发语言·人工智能·python·microsoft·搜索引擎·ai
Zhou1411361 小时前
SpringBoot_03_Web开发
前端·spring boot·python
weixin199701080161 小时前
《1688物流API接口边界:logistics.trace.get 与 freight.template.list 的隐藏约束》(附Python源码)
windows·python·list
朝朝辞暮i1 小时前
C++ 第 4 课:if / else —— 让程序自己做决定
开发语言·c++