我在函数中有以下代码:
stored_blocks = {}
def replace_blocks(m):
block = m.group(0)
block_hash = sha1(block)
stored_blocks[block_hash] = block
return '{{{%s}}}' % block_hash
num_converted = 0
def convert_variables(m):
name = m.group(1)
num_converted += 1
return '<%%= %s %%>' % name
fixed = MATCH_DECLARE_NEW.sub('', template)
fixed = MATCH_PYTHON_BLOCK.sub(replace_blocks, fixed)
fixed = MATCH_FORMAT.sub(convert_variables, fixed)
Run Code Online (Sandbox Code Playgroud)
添加元素stored_blocks工作正常,但我不能增加num_converted第二个子功能:
UnboundLocalError:赋值前引用的局部变量'num_converted'
我可以使用,global但全局变量是丑陋的,我真的不需要该变量是全局的.
所以我很好奇如何写入父函数范围内的变量.
nonlocal num_converted可能会完成这项工作,但我需要一个适用于Python 2.x的解决方案.
Python中是否有一种方法可以访问匹配组而无需明确创建匹配对象(或另一种方式来美化下面的示例)?
这是一个澄清我的问题动机的例子:
遵循perl代码
if ($statement =~ /I love (\w+)/) {
print "He loves $1\n";
}
elsif ($statement =~ /Ich liebe (\w+)/) {
print "Er liebt $1\n";
}
elsif ($statement =~ /Je t\'aime (\w+)/) {
print "Il aime $1\n";
}
Run Code Online (Sandbox Code Playgroud)
翻译成Python
m = re.search("I love (\w+)", statement)
if m:
print "He loves",m.group(1)
else:
m = re.search("Ich liebe (\w+)", statement)
if m:
print "Er liebt",m.group(1)
else:
m = re.search("Je t'aime (\w+)", statement)
if m:
print "Il aime",m.group(1)
Run Code Online (Sandbox Code Playgroud)
看起来很尴尬(if-else-cascade,匹配对象创建).