4
from docx import *
document = Document('ABC.docx')

for paragraph in document.paragraphs:
 for run in paragraph.runs:
  if run.style == 'Strong':
   print run.text

这是我用来打开 docx 文件并检查是否有粗体文本但我没有得到任何结果的代码。如果我删除 if 语句,则打印整个文件而没有任何格式/样式。您能否让我知道如何使用 python-docx 识别特定样式的文本,例如粗体或斜体?谢谢

4

2 回答 2

14

尽管在渲染时粗体和样式Strong看起来相同,但它们使用了两种不同的机制。第一个直接应用粗体,第二个应用可以包含任何其他数量的字体特征的字符样式。

要识别所有出现的粗体文本您可能需要同时执行这两项操作。

但是要找到应用了粗体的文本,您可以执行以下操作:

for paragraph in document.paragraphs:
    for run in paragraph.runs:
        if run.bold:
            print run.text

请注意,这可能会遗漏显示为粗体的文本,例如出现在整个段落的字体格式为粗体的段落中的文本(例如,标题 1)。但我认为这是您正在寻找的财产。

于 2015-01-12T21:21:41.240 回答
0

要检查特定样式,您可以使用name可用的属性_ParagraphStyle objects_CharacterStyle objects

例子:

for paragraph in document.paragraphs:
    if 'List Paragraph' == paragraph.style.name:
        print(paragraph.text)
于 2019-03-05T10:48:06.670 回答