用Python解析docx文件

问题描述 投票:1回答:1

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

一只猫

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文件中这些特定标题的格式或结构没有什么独特之处。

python regex python-docx
1个回答
1
投票

发生的事情是循环继续经过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)
© www.soinside.com 2019 - 2024. All rights reserved.