在Python中解析docx文件

2024-10-01 13:29:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从多个docx文件中读取标题。令人恼火的是,这些标题没有可识别的段落样式。所有段落都有“正常”段落样式,所以我使用正则表达式。标题采用粗体格式,结构如下:

A.猫

B.狗

C.猪

D.福克斯

如果一个文件中有超过26个标题,那么这些标题前面会加上“AA.”、“BB.”等

我有下面的代码,除了前面有“D”的标题外,哪种代码可以打印两次。 [猫,狗,猪,狐狸,狐狸]

import os
from docx import Document
import re

directory = input("Copy and paste the location of the files.\n").lower()

for file in os.listdir(directory):

    document = Document(directory+file)

    head1s = []

    for paragraph in document.paragraphs:

        heading = re.match(r'^[A-Z]+[.]\s', paragraph.text)

        for run in paragraph.runs:

            if run.bold:

                if heading:
                    head1 = paragraph.text
                    head1 = head1.split('.')[1]
                    head1s.append(head1)

    print(head1s)

有人能告诉我是不是代码有问题导致了这种情况的发生?据我所知,Word文件中这些特定标题的格式或结构没有什么独特之处。在


Tags: 文件代码inimport标题for格式样式
1条回答
网友
1楼 · 发布于 2024-10-01 13:29:17

所发生的是循环继续超过D.Fox,因此在这个新的循环中,即使没有匹配项,它仍打印head1的最后一个值,即D.Fox。在

我认为是for run in paragraph.runs:以某种方式运行了两次,也许还有第二次“运行”在那里,但看不见?在

也许在找到第一个匹配时添加一个中断足以防止第二次运行触发?在

for file in os.listdir(directory):

document = Document(directory+file)

head1s = []

for paragraph in document.paragraphs:

    heading = re.match(r'^[A-Z]+[.]\s', paragraph.text)

    for run in paragraph.runs:

        if run.bold:

            if heading:
                head1 = paragraph.text
                head1 = head1.split('.')[1]
                head1s.append(head1)
                # this break stops the run loop if a match was found.
                break

print(head1s)

相关问题 更多 >