Extracting headings' text from word doc

Muhammad Muaz picture Muhammad Muaz · Nov 2, 2016 · Viewed 7.2k times · Source

I am trying to extract text from headings(of any level) in a MS Word document(.docx file). Currently I am trying to solve using python-docx, but unfortunately I am still not able to figure out if it is even feasible after reading it(maybe I am mistaken).

I tried to look for the solutions online but found nothing specific to my task. It would be great if someone could guide me here.

Answer

scanny picture scanny · Nov 3, 2016

The fundamental challenge is identifying heading paragraphs. There's nothing stopping an author from formatting a "regular" paragraph to look like (and serve as) a heading as far as a reader is concerned.

However, it's not uncommon for authors to reliably use styles to create headings, because doing so makes it possible to automatically compile those headings into a table of contents.

In that case, you can just iterate over the paragraphs, and pick out those with one of the heading styles.

def iter_headings(paragraphs):
    for paragraph in paragraphs:
        if paragraph.style.name.startswith('Heading'):
            yield paragraph

for heading in iter_headings(document.paragraphs):
    print heading.text

Heading levels may be parsed from the full style name if they've kept the defaults (like 'Heading 1', 'Heading 2', ...).

This may need to be adjusted if the author has renamed the heading styles.

There are more sophisticated approaches which are more reliable (as far as being style-name independent), but those don't have API support so you'd need to dig into the internal code and interact with some of the style XML directly I expect.