Python - LibreOffice Calc - 用正则表达式查找和替换
问题描述:
我尝试编码查找&在LibreOffice的Calc中用Python替换方法,用“&”替换所有“。+”(在单个列中 - 不是那么重要) - 不幸的是,即使是一个标准的查找&替换方法似乎是不可能的(对我来说)。这就是我现在所知道的:Python - LibreOffice Calc - 用正则表达式查找和替换
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
然后会发生什么:完全没有!我会很高兴和感谢每一个提示,示例代码和激励的话!
答
这段代码改变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:
&将插入搜索RegExp找到相同的字符串。
所以替换字符串需要是文字 - \&
。
我对你的代码做了一些微小的改动,但总的来说它工作得很好。非常感谢! – Elsi