Python-docx: How to get the text in the tag 'smartTag' ?

Created on 25 Oct 2016  路  3Comments  路  Source: python-openxml/python-docx

I use this package to extract text from a docx file, but I find that the text in the tag 'smartTag' will be ignored when I using paragraph.text.
Is there another function I can use to do that ?

Most helpful comment

Instead of using paragraph.text, using the following function:

def para2text(p):
    rs = p._element.xpath('.//w:t')
    return u" ".join([r.text for r in rs])

All 3 comments

For now, you will have to do this with an extension function or similar approach.

The general idea is:

  1. Get the paragraph element (w:p) from the paragraph object

python p = paragraph._element

  1. Retrieve the run elements using XPath

python rs = p.xpath('//w:r')

  1. Construct your own Run objects from the w:r elements:

python runs = [Run(r, None) for r in rs]

This is air code, so you may need to work out the finer points. But this is how I would approach the problem.

Thanks, now I know how to get all the text.
But in this way I lose the message of paragraph, in fact I want parsing the text as paragraphs.
I'm trying to read the source code to find the way build paragraph, but it's too big to understand. @scanny

Instead of using paragraph.text, using the following function:

def para2text(p):
    rs = p._element.xpath('.//w:t')
    return u" ".join([r.text for r in rs])
Was this page helpful?
0 / 5 - 0 ratings

Related issues

scanny picture scanny  路  8Comments

ssuzen picture ssuzen  路  6Comments

ronbarak picture ronbarak  路  3Comments

madphysicist picture madphysicist  路  3Comments

norecces picture norecces  路  7Comments