下面的代码是我正在处理的css预处理程序的一部分。本节接受用户定义的变量并将它们插入到代码中。regex只在它被空格、大括号、括号、逗号、引号或运算符包围时才会替换。当我运行它时,我只需要每隔一次更换一次变量。
def insert_vars(ccss, variables):
for var in variables.keys():
replacer = re.compile(r"""(?P<before>[,+\[(\b{:"'])\$""" + var + """(?P<after>[\b}:"'\])+,])""")
ccss = replacer.sub(r"\g<before>" + variables[var] + r"\g<after>", ccss)
del replacer
re.purge()
return ccss.replace(r"\$", "$")当我运行它时
insert_vars("hello $animal, $nounification != {$noun}ification.", {"animal": "python", "noun": "car"})50%的时间回来
hello $animal, $nounification != {car}ification.其余50%
hello $animal, $nounification != {$noun}ification.有人知道为什么吗?
发布于 2014-09-21 13:29:55
发生的情况是,您的return关键字是循环的一部分,作为acjr stated in the comments。
这意味着循环只运行一次迭代。
.keys()的排序是未定义的,'animal'或'noun'都可以放在第一位。
有一半时间,您的代码将首先获得'noun',这将正确工作,或获得'animal'优先,这将不会有任何影响。
因此,您应该将return的缩进减少到循环之外。
发布于 2014-09-21 16:24:42
def insert_vars(ccss, variables):
pattern = re.compile(r"\$(?P<key>\w+)")
def replacer(match):
return variables.get(match.group('key'), match.group(0))
return pattern.sub(replacer, ccss)https://stackoverflow.com/questions/25959548
复制相似问题