Search and replace text odfpy

Question:

I’m trying to make reports for a program using odfpy. My idea is to search for each keywords like [[[e_mail_address]]] and replace it by a word from the database.
I found the function text in odfpy api, but converted into string looses the formating.
There is an document in the odfpy installation files: api-for-odfpy.odt. In point 6.2 Teletype module, there is written how to get all the texts from the document and put them into a 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 the method to replace the current text to another. Maybe:

text.Change()

but there is always an error while using it. If you have any experience in using odfpy, please help.

Asked By: Maciek

||

Answers:

I already found an 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')
Answered By: Maciek

Sorry for needing to Answer this.
Sadly I am not able to comment as I have made an account just for this question.

some things i want to remark:

  • i think your code should include the import statements in the answer as well, as that threw me off a little.
  • this way of iterating over the texts is not working (anymore?).
    for i in range(s-1, -1, -1):
    

    this works as of writing

  • you should use double-quotes on both occasions when referring to the filename
Answered By: haennes
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.