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()
        
相关推荐
m0_4954964113 小时前
SQL批量更新状态机字段_使用CASE表达式一次性处理
jvm·数据库·python
2401_8504916513 小时前
Python处理分类不平衡问题_使用平衡随机森林提升召回率
jvm·数据库·python
终生成长者13 小时前
04LangChain SQL 问答系统知识点详解
数据库·python·sql·langchain
m0_7335654613 小时前
Golang Redis Pipeline如何用_Golang Redis Pipeline教程【完整】
jvm·数据库·python
admiraldeworm13 小时前
c -> true 导致异常返回 404 问题排查
c语言·开发语言
翎刿13 小时前
AttributeError: ‘FigureCanvasInterAgg‘
python
2401_8676239813 小时前
golang如何实现布隆过滤器_golang布隆过滤器实现教程
jvm·数据库·python
m0_7407963613 小时前
golang如何编写Markdown转HTML工具_golang Markdown转HTML工具编写详解
jvm·数据库·python
2403_8832610913 小时前
CSS如何实现Bootstrap进度条自定义动画_利用keyframe关键帧
jvm·数据库·python
2301_7693406713 小时前
CSS如何兼容新旧方案结合响应式容器查询
jvm·数据库·python