Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace text odfpy

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.

like image 730
Maciek Avatar asked Nov 12 '14 12:11

Maciek


1 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')
like image 112
Maciek Avatar answered Nov 11 '22 14:11

Maciek