如何使用 python-docx 增加 word 文档中的段落 object?

How to increment paragraph object in word document using python-docx?

我正在搜索 word 文档以获取文档中所写内容的描述。但是,这些文档的格式并不完全相同。但有一件事是一致的,我想要的文本块总是在标题 'Description' 之后。所以我会搜索 'Description' 然后希望在它之后得到下一段 object 的文本。我如何增加段落 object(可以这么说)?

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        doc = docx.Document(os.path.join(rootdir, file))
        for paragraph in doc.paragraphs:
            if 'Description' in paragraph.text:
                print(paragraph[i+1].text) #I know you can't do i+1 but
                                           #that's essentially what I want to do

如果您希望以这种方式提取文本并进行搜索,python-docx2txt 会让您感到头疼。它改编自 python-docx.

一个简单的方法是:

paragraphs = list(doc.paragraphs)

for i in range(len(paragraphs)):
    paragraph = paragraphs[i]
    if 'Description' in paragraph.text:
        print(paragraphs[i+1].text)

如果您确定描述标签出现在具有 Heading 1 样式的段落中,您可以进一步限定标题段落,这样您就不会在恰好使用该词的段落中得到误报.