【发布时间】:2018-05-24 10:07:28
【问题描述】:
我正在尝试从多个 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 文件中这些特定标题的格式或结构并没有什么独特之处。
【问题讨论】:
标签: python regex python-docx