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

标签 python linux scripting libreoffice

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

我想用 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 .

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

这是一个 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")

关于LibreOffice 的 Python 宏 - 替换文本中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36626736/

相关文章:

python - 我所有的测试函数都在加载 conftest.py 中的 fixture ,即使它们不需要它

python - 使用 NumPy 从特征值创建 Jordan 矩阵

php - 在 Linux 的 joinWith(YII2) 中添加别名不起作用

Linux cron 作业无法执行在 shell 中运行的部分脚本

bash - 将 awk 的结果放入数组中

python - Qt:QPushButton 被子进程阻塞

python - 检索无堆栈 Python Tasklet 绑定(bind)函数的返回值?

linux - 桌面文件不执行命令

linux - 运行从 stdin 管道传输的脚本(Linux/Shell 脚本)

javascript - 正则表达式说明