Python - LibreOffice Calc - 使用正则表达式查找和替换
Python - LibreOffice Calc - Find & Replace with Regular Expression
我尝试在 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
然后发生了什么:完全没有!对于每一个提示、示例代码和激励性的话语,我都会感到高兴和感激!
此代码将 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 to actually do something. Also, from the User Guide:
& will insert the same string found with the Search RegExp.
所以替换字符串需要是文字 -- \&
.
我尝试在 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
然后发生了什么:完全没有!对于每一个提示、示例代码和激励性的话语,我都会感到高兴和感激!
此代码将 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 to actually do something. Also, from the User Guide:
& will insert the same string found with the Search RegExp.
所以替换字符串需要是文字 -- \&
.