有没有什么方法可以直接从docx段落而不是元数据中迭代得到docx文件的标题



使用下面给出的代码,我得到了docx文件的标题。更确切地说,标题是第一页上字体最大的文本。但我的问题是,当我编辑同一个docx文件的第一页,并使其他文本字体比forst页面上的前一个文本大时,我现在无法获得我想要的输出文本。它给出的是相同的旧输出,而不是新编辑的大字体文本。我正在使用ubuntu。

import docx
doc = docx.Document('/home/user/Desktop/xyz.docx')
print("The first line of document is:", doc.paragraphs[0].text)
list = []
for p in doc.paragraphs:
size = p.style.font.size
if size != None:
size = p.style.font.size.pt
list.append(size)
print(list)
print(max(list))
for paragraph in doc.paragraphs:
size = paragraph.style.font.size
if size != None:
if paragraph.style.font.size.pt == max(list):
print(paragraph.text)

标题通常应该在第一页,也可以不在第一段。您可以迭代段落并查找具有明确名称"的样式;标题";其将该段落标记为标题样式,或者如果在Word文档中没有明确定义标题样式。

import docx
doc = docx.Document('xyz.docx')
title_size = max_size = 0
max_size_text = title = None
for p in doc.paragraphs:
style = p.style
if style is not None:
if style.name == 'Title':
title_size = style.font.size.pt
title = p.text
break
size = style.font.size
if size is not None:
if size.pt > max_size:
max_size = size.pt
max_size_text = p.text
if title is not None:
print(f"Title: size={title_size} text='{title}'")
else:
print(f"max size title: size={title_size} text='{max_size_text}'")

如果title为None,则未定义显式标题,则可以使用具有最大点大小的文本。

最新更新