我试图更好地了解lambda函数和正则表达式匹配如何在Python中工作。为此,我将lambda替换为命名函数。
即使我找到了使它起作用的方法,但我仍然无法理解它为什么起作用。
我正在处理的lambda / regex是以下帖子中提到的:
这是主要的代码段:
import re
# define desired replacements here
rep = {"condition1": "", "condition2": "text"}
text = "(condition1) and --condition2--"
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.items())
pattern = re.compile("|".join(rep.keys()))
output = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
print(output)
>>> '() and --text--'
如果我将lambda函数替换为:
def replace_conditions(match, rep):
return rep[re.escape(match.group(0))]
output = pattern.sub(replace_conditions(m, rep), text)
我得到以下异常:
NameError: name 'm' is not defined
而且我能够使用以下语法使其工作:
def replace_conditions(match, rep=rep):
return rep[re.escape(match.group(0))]
output = pattern.sub(replace_conditions, line)
注意:我必须为第二个参数“ rep”预先分配一个值,并使用函数的名称,而无需实际调用它。
我不明白为什么不使用正则表达式将正则表达式表达式返回的匹配正确传递给函数,而使用常规语法调用时不将其传递给第一个参数。
我不明白为什么如果不带参数调用正则表达式表达式返回的匹配项正确传递给函数
那不是正在发生的事情。pattern.sub(replace_conditions, line)
不调用该replace_conditions
函数,它只是将其传递。
从文档中获取:
re.sub(pattern, repl, string, count=0, flags=0)
与以下内容相同:
pattern.sub(repl, string)
如果
repl
是函数,则在每次非重叠发生模式时都会调用它。该函数采用单个match对象参数,并返回替换字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句