gpt4 book ai didi

python - 在Python中解析docx文件

转载 作者:行者123 更新时间:2023-12-01 09:24:59 25 4
gpt4 key购买 nike

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

A.猫

B.狗

C. pig

D.狐狸

如果文件中的标题超过 26 个,则标题前面将带有“AA.”、“BB.”等

我有以下代码,除了以“D.”开头的任何标题打印两次之外,该代码都有效,例如[猫、狗、 pig 、狐狸、狐狸]

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

最佳答案

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

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

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

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)

关于python - 在Python中解析docx文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com