想要从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