-2

1)I would like to swap certain keywords in an odf document programmatically. For example, the sample lease has TENANT_NAME, and my program would insert the actual name of the tenant.

  1. I have tried a code snippet from this website that works on simple documents, but when I try to use it on my lease it throws an index out of range error.
from odf import opendocument, text, teletype

this_dictionary = {
    'TENANT_NAME': 'Cameron Stark',
    'DATE_START': '5/1/2022',
    'DATE_END': '7/31/2022',
    'RENT_AMOUNT': '500',
    'DEPOSIT_AMOUNT': '400',
    'EMAIL_ADDRESS': 'example@ymail.com',
    'PHONE_NUMBER': '1234567890'
}

PATH = "C:/Users/Cameron Stark/Documents/sample_lease_alpine.odt"
DESTINATION = "C:/Users/Cameron Stark/Documents/cameron_lease.odt"


def change_odt_file(my_dictionary, path, destination):
    text_doc = opendocument.load(path)
    for x, y in my_dictionary.items():
        texts = text_doc.getElementsByType(text.P)
        s = len(texts)
        for i in range(s):
            old_text = teletype.extractText(texts[i])
            new_text = old_text.replace(x, y)
            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])
        text_doc.save(destination)
        text_doc = opendocument.load(destination)


change_odt_file(this_dictionary, PATH, DESTINATION)
  • Without knowing what exactly is your document like, I can only offer a suggestion to use a different parameter name other than ```dict``` Have you printed out what ```x``` and ```y``` are after ```for x, y in dict.items():```? – ewokx Apr 18 '22 at 23:43
  • You usually don't get downvoted for difficult questions, but for questions that show no effort on your side to solve the problem, or for questions that are unclear and missing details, pure code dumps, or if you sound too pushy and entitled, or for vague problem descriptions. In your case, describing clearly where that error happens would help. Also include the odt file, for a [mcve]. – Robert May 01 '22 at 05:02

1 Answers1

0

Simple solution, just re-write my lease in HTML. Super easy to work with and more capability than any word-processing software.