Python LibreOffice 宏 - 替换文本中的字符串

Python macro for LibreOffice - replace string in text

我一直在寻找一些关于此的用户友好教程,但没有找到。

我想在 Python 中为 LibreOffice 编写一个宏,它将替换 Writer 中当前打开的文档中的字符串。令人惊讶的是,似乎没有来自开发人员或用户的任何官方指南、文档甚至示例。

我需要知道的是,如何在 Python 中访问当前打开的文档的文本并更改它?工作示例会很棒,但非常感谢任何帮助。

一个简单的"Hello World"例子如下:

def hello():
    XSCRIPTCONTEXT.getDocument().getText().setString("Hello!")

# Functions that can be called from Tools -> Macros -> Run Macro.
g_exportedScripts = hello,

参见https://wiki.openoffice.org/wiki/Python/Transfer_from_Basic_to_Python

如何搜索和替换文本取决于您的要求。替换一次还是全部?替换为普通文本,还是替换为表格、框架或 headers 等元素?区分大小写,或者可能是正则表达式?有关基本示例,请参阅 Andrew Pitonyak's macro document 中的第 7.14 节。

这是 Python 中的一个工作示例,它将所有出现的 "search for" 更改为 "change to":

document = XSCRIPTCONTEXT.getDocument()
search = document.createSearchDescriptor()
search.SearchString = "search for"
search.SearchAll = True
search.SearchWords = True
search.SearchCaseSensitive = False
selsFound = document.findAll(search)
if selsFound.getCount() == 0:
    return
for selIndex in range(0, selsFound.getCount()):
    selFound = selsFound.getByIndex(selIndex)
    selFound.setString("change to")