我想使用Python编辑ODT文档。只是一个简单的关键字交换。这可能吗?
1)我想以编程方式在ODF文档中交换某些关键字。例如,样本租赁具有tenant_name,我的程序将插入租户的实际名称。
- 我尝试了该网站上使用的代码段,可用于简单文档,但是当我尝试在租赁上使用它时,它会引发索引范围错误。
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': '[email protected]',
'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)
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.
- 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': '[email protected]',
'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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的解决方案,只需在HTML中重写我的租约即可。与任何单词处理软件相比,使用的功能非常易于使用,并且能力更大。
Simple solution, just re-write my lease in HTML. Super easy to work with and more capability than any word-processing software.