Python:使用def定义一个匿名函数以在re.sub中使用



我还没能找到一个答案,这是否合法。这是一个查找和替换字符串中所有"变量"的函数。(以v_开头的单词)。我不能使用lambda,因为我需要多行替换函数,因为需要使用&;if&;条款。

def fillin(template, dictionary):
result = re.sub(r'v_([a-z_]+)', def(match):
variable = match.group(1)
if not variable in dictionary:
return match # don't replace nuthin'                                                   
return dictionary[variable],
Scene )
return result

获取文本中所有以v_开头的字符串,然后查看字符串的其余部分以获取"变量名",在字典中查找该变量名,并用查找到的值替换字符串。

我不能使用lambda,因为我需要在dictionary"子句,以防止在字典中查找错误。

有没有办法使用def匿名函数?

我想这个lambda适合你。

lambda match: match if not match.group(1) in dictionary else dictionary[match.group(1)]

您可以使用lambda,如果您使用dictionary.get(x.group(1), x.group()),则仍然保持简短:

re.sub(r'v_([a-z_]+)', lambda x: dictionary.get(x.group(1),x.group()), text)

参见Python演示:

import re
text = "aaa v_abc v_def"
dictionary = { 'abc':'yes' }
print( re.sub(r'v_([a-z_]+)', lambda x: dictionary.get(x.group(1),x.group()), text) )
# => aaa yes v_def

在调用re的位置之前定义函数。然后将函数作为普通参数传递。"def"声明为函数提供了一个名称,该名称引用函数的方式与本地"lambda"表达式。

def replacer(match):
variable = match.group(1)
if not variable in g_dictionary:
return match # don't replace nuthin'                                                   
return dictionary[variable]
def fillin(template, dictionary):
global g_dictionary
g_dictionary
result = re.sub(r'v_([a-z_]+)', replacer, Scene)
return result

上面的例子将dictionary重新赋值给一个全局变量,这样它就可以在另一个函数中看到。更常用的方法是定义嵌套函数,如下面的例子所示。

在这种情况下,您需要访问"dictionary"它是外部作用域中的一个变量,你可以定义嵌套在fillin中的replacer——这正是你定义lambda函数时发生的事情。:


def fillin(template, dictionary):
def replacer(match):
variable = match.group(1)
if not variable in dictionary:
return match # don't replace nuthin'                                                   
return dictionary[variable]
result = re.sub(r'v_([a-z_]+)', replacer, Scene)
return result

最新更新