使用python-docx检查特定样式

Vij*_*avi 2 python-docx

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

for paragraph in document.paragraphs:
 for run in paragraph.runs:
  if run.style == 'Strong':
   print run.text
Run Code Online (Sandbox Code Playgroud)

这是我用来打开docx文件并检查是否有粗体文本但我没有得到任何结果的代码.如果我删除if语句,则打印整个文件时没有任何格式/样式.你能告诉我如何使用python-docx识别像Bold或Italics这样的特定文本的文本吗?谢谢

sca*_*nny 9

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

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

但是要找到大胆应用的文本,你会做这样的事情:

for paragraph in document.paragraphs:
    for run in paragraph.runs:
        if run.bold:
            print run.text
Run Code Online (Sandbox Code Playgroud)

请注意,有些方法可能会错过显示为粗体的文本,例如出现在段落中的文本,其字体格式为整个段落的粗体(例如Heading1).但我认为这是你正在寻找的财产.