Checking for particular style using python-docx

不羁岁月 提交于 2020-07-18 06:29:45

问题


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


回答1:


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.




回答2:


To check for a particular style you could use the name property that is available in _ParagraphStyle objects or _CharacterStyle objects

example:

for paragraph in document.paragraphs:
    if 'List Paragraph' == paragraph.style.name:
        print(paragraph.text)


来源:https://stackoverflow.com/questions/27904470/checking-for-particular-style-using-python-docx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!