Checking for particular style using python-docx

11,023

Although bold and the style Strong appear the same when rendered, they use two different mechanisms. The first applies bold directly and the second applies a character style that can include any other number of font characteristics.

To identify all occurrences of text that appears bold, you may need to do both.

But to just find the text having bold applied you would do something like this:

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

Note there are ways this can miss text that appears bold, like text that appears in a paragraph whose font formatting is bold for the entire paragraph (Heading1 for example). But I think this is the property you were looking for.

Share:
11,023
Vijayaraghavan Ravi
Author by

Vijayaraghavan Ravi

Updated on June 22, 2022

Comments

  • Vijayaraghavan Ravi
    Vijayaraghavan Ravi about 2 years
    from docx import *
    document = Document('ABC.docx')
    
    for paragraph in document.paragraphs:
     for run in paragraph.runs:
      if run.style == 'Strong':
       print run.text
    

    This is the code I am using to open a docx file and to check if there is Bold text but I am not getting any result. If I remove the if statement , the entire file is printed without any formatting / styles. Can you please let me know how to identify text in particular style like Bold or Italics using python-docx ? Thank you

  • Vijayaraghavan Ravi
    Vijayaraghavan Ravi over 9 years
    Can you tell me how to identify Italics text ? Is there a generic documentation available for this ?
  • scanny
    scanny over 9 years
    There's also a Run.italics property which operates similarly to .bold. The documentation has more on that here: python-docx.readthedocs.org/en/latest/api/text.html#run-obje‌​cts
  • Tarek B
    Tarek B over 5 years
    @scanny do you know a way how to check for 'List Paragraph' == paragraph.style for a given paragraph ? or any other style ?
  • Tarek B
    Tarek B over 5 years
    ok, i figured it out i just need to use the name property on _ParagraphStyle objects so it is 'List Paragraph' == paragraph.style.name