Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting headings' text from word doc

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.

like image 806
Muhammad Muaz Avatar asked Nov 02 '16 20:11

Muhammad Muaz


People also ask

How do I separate headings and text in Word?

One solution is to place the cursor at the beginning of the paragraph that you don't want to be collapsed with the heading, and then insert a continuous section break (on the Layout tab, in the Page Setup group, click Breaks > Continuous).

How do you separate headings?

Select Layout > Breaks > Next Page. Double-click the header or footer on the first page of the new section. Click Link to Previous to turn it off and unlink the header or footer from the previous section. Note: Headers and footers are linked separately.

How do I extract text from multiple text boxes in Word?

Press “Ctrl” and click those text box names on the pane one by one to select them all. And move to lay cursor on one of the box line and right click. On the list-option, click “Copy”. Now if you won't need those boxes anymore, just press “Delete”.


1 Answers

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.

like image 145
scanny Avatar answered Sep 22 '22 12:09

scanny