【问题标题】:Python - LibreOffice Calc - Find & Replace with Regular ExpressionPython - LibreOffice Calc - 使用正则表达式查找和替换
【发布时间】:2016-07-15 07:40:18
【问题描述】:

我尝试在 LibreOffice 的 Calc 中使用 Python 编写查找和替换方法,以将所有“.+”替换为“&”(在单个列中 - 不那么重要) - 不幸的是,即使是标准的查找和替换方法似乎不可能(对我来说)。这就是我现在所拥有的:

import uno
def search()
    desktop = XSCRIPTCONTEXT.getDesktop()
    document = XSCRIPTCONTEXT.getDocument()
    ctx = uno.getComponentContext()
    sm = ctx.ServiceManager
    dispatcher = sm.createInstanceWithContext("com.sun.star.frame.DispatchHelper", ctx)
    model = desktop.getCurrentComponent()
    doc = model.getCurrentController()
    sheet = model.Sheets.getByIndex(0)

    replace = sheet.createReplaceDescriptor()
    replace.SearchRegularExpression = True
    replace.SearchString = ".+$"
    replace.ReplaceString ="&"
    return None

然后会发生什么:完全没有!我会很高兴并感谢每一个提示、示例代码和激励词!

【问题讨论】:

    标签: python libreoffice libreoffice-calc uno


    【解决方案1】:

    此代码将 A 列中的所有非空单元格更改为 &

    def calc_search_and_replace():
        desktop = XSCRIPTCONTEXT.getDesktop()
        model = desktop.getCurrentComponent()
        sheet = model.Sheets.getByIndex(0)
        COLUMN_A = 0
        cellRange = sheet.getCellRangeByPosition(COLUMN_A, 0, COLUMN_A, 65536);
        replace = cellRange.createReplaceDescriptor()
        replace.SearchRegularExpression = True
        replace.SearchString = r".+$"
        replace.ReplaceString = r"\&"
        cellRange.replaceAll(replace)
    

    请注意,代码调用replaceAll 来实际执行某些操作。另外,来自User Guide

    & 将插入使用 Search RegExp 找到的相同字符串。

    所以替换字符串需要是文字——\&

    【讨论】:

    • 我对您的代码做了一些微小的更改,但总的来说效果很好。非常感谢!
    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多