python-docx获取docx文档多级目录

本文介绍了如何使用python-docx库解析docx文件的多级目录。通过分析`add_heading()`函数源码,发现标题被视为具有特定样式的段落。通过判断段落样式,识别标题并实现排序。尽管未能找到标题序号的直接获取方法,但分享了当前实现标题提取的代码。
摘要由CSDN通过智能技术生成

        想要从docx文档中读取各层目录,即便是翻了官方文档,也没有找到对应内容,最后看了代码,总算是略有所得,写篇文章记录一下。

        python-docx中与标题相关有一个函数,添加标题,add_heading(),我就是从这个函数入手的。翻了下源码,这个函数是这样的,下面附上源码。

    def add_heading(self, text="", level=1):
        """Return a heading paragraph newly added to the end of the document.

        The heading paragraph will contain *text* and have its paragraph style
        determined by *level*. If *level* is 0, the style is set to `Title`. If *level*
        is 1 (or omitted), `Heading 1` is used. Otherwise the style is set to `Heading
        {level}`. Raises |ValueError| if *level* is outside the range 0-9.
        """
        if not 0 <= level <= 9:
            raise ValueError("level must be in range 0-9, got %d" % level)
        style = "Title" if level == 0 else "Heading %d" % leve
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值