Search and replace odfpy text

I am trying to make reports for a program using odfpy. My idea is to search for all keywords, such as [[[e_mail_address]]] and replace it with a word from the database. I found the function text in odfpy api, but converted to string is losing shape. There is a document in fuzzy installation files: api-for-odfpy.odt. In paragraph 6.2 of the Teletype module it is written how to get all the texts from the document and put them in the list:

from odf import text, teletype
from odf.opendocument import load

textdoc = load("my document.odt")
allparas = textdoc.getElementsByType(text.P)
print teletype.extractText(allparas[0])

and now I'm looking for a method to replace the current text with another. May be:

text.Change()

but there’s always a mistake when using it. If you have experience using odfpy, please help.

+4
source share
1 answer

:

textdoc = load("myfile.odt")
texts = textdoc.getElementsByType(text.P)
s = len(texts)
for i in range(s):
    old_text = teletype.extractText(texts[i])
    new_text = old_text.replace('something','something else')
    new_S = text.P()
    new_S.setAttribute("stylename",texts[i].getAttribute("stylename"))
    new_S.addText(new_text)
    texts[i].parentNode.insertBefore(new_S,texts[i])
    texts[i].parentNode.removeChild(texts[i])
textdoc.save('myfile.odt')
+6

All Articles