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()
        
相关推荐
MC皮蛋侠客2 分钟前
SQLAlchemy 系列(八):AsyncIO、并发与 Web 生命周期——让每个并发任务持有自己的 Session
数据库·python
程序员zgh11 分钟前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++
念何架构之路15 分钟前
restartmanager-重启管理子系统
java·开发语言
SomeB1oody1 小时前
【RustyML入门】2.0. 经典机器学习
开发语言·后端·机器学习·rust·教程
大数据魔法师1 小时前
Python 网络请求库 curl_cffi:从入门到实战,如何规避网站指纹检测
python·数据分析
中电华星1 小时前
专业的工业电源公司
网络·python
databook2 小时前
用统计检验来确定“重要特征”
python·机器学习·scikit-learn
0566462 小时前
Python高级——解释器执行原理与虚拟环境工程化实战
开发语言·python
weixin_435776112 小时前
2026年长沙托育vi设计从风格定位到元素运用的设计方法
linux·运维·服务器·python
梦想三三2 小时前
LangChain RAG PDF 智能问答实战:用 Streamlit 构建本地知识库(完整代码)
人工智能·python·langchain·大模型·rag