1
votes

I've been trying to find a way to change all the bullet lists in a docx file to number list using python-docx. So far, I've tried using paragraph.style attribute. Doing something like this:

if paragraph.style.name == 'Bullet List':
    paragraph.style = styles['List Number']

It works on basic docx files but sometimes, with more complex documents, paragraph.style.name returns something like 'Body Text' even though the given paragraph appears as a bullet list in the document. I was just wondering if it's possible to achieve this using python-docx library or I might have to look for something else. Thank you.

1

1 Answers

0
votes

The short answer is no. What you're seeing are bullets applied to a paragraph using the toolbar button, which applies the bullet formatting directly to the paragraph. Any formatting applied at the paragraph level (the lowest level) overrides formatting inherited from a style.

What you'd need to do to fix this is to remove the manual paragraph formatting (possibly by selecting paragraphs and pressing Ctrl-Q) as described here and in other web resources as well I'm sure: https://www.okbar.org/lpt_articles/removing-formatting-from-word-documents/

After those "overrides" are removed, the style should be free to do its work.

There is no python-docx API counterpart to "remove-all-formatting". If you wanted to do it programmatically you would need to manipulate the XML yourself. python-docx can get you to the paragraph element with p = paragraph._p and then print(p.xml) can show you what the XML looks like, but from there you're on your own to manipulate that XML subtree with lxml calls. Search on python-docx workaround function for some ideas on what that looks like.