如何将变量传递给re.sub回调? [英] How to pass a variable to a re.sub callback?

查看:57
本文介绍了如何将变量传递给re.sub回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用re.sub回调将子字符串替换为随机值,但是我希望不同字符串中的随机值相同。由于re.sub回调不允许使用参数,因此我不确定如何执行此操作。

I am using a re.sub callback to replace substrings with random values, but I would like the random values to be the same across different strings. Since the re.sub callback does not allow arguments, I am not sure how to do this.

以下是我正在做的工作的简化版本:

Here is a simplified version of what I'm doing:

def evaluate(match):
    mappings = {'A': 1, 'B': 2}
    return str(eval(match.group(0)[2:-1], mappings))

# variables = {'A':[1,2,3,4,5], 'B':[1,2,3,4,5]}    
# mappings2 = {k:v[random.randint(0,len(v)-1)] for k, v in variables.items()}
string_one: "#{A} + #{B}"
string_two: "#{A+B}"
newstring_one = sub(r'\#\{([^#]+)\}', evaluate, string_one)
newstring_two = sub(r'\#\{([^#]+)\}', evaluate, string_two)

现在,就目前而言,将正确评估字符串:newstring_one为 1 + 2,newstring_two为 3。但是我希望能够随机选择这些值,并且仍将其替换为两个字符串。这将涉及删除评估中的映射行,并使用两条注释行之类的东西。但是,如果我无法在re.sub回调函数中将其作为参数传递时,如何在评估两个字符串时使用随机选择的映射2?

Now, as it stands, the strings will be properly evaluated: newstring_one is "1 + 2" and newstring_two is "3". But I want to be able to pick the values randomly, and still have them replaced in both strings. This would involve deleting the 'mappings' line in 'evaluate', and using something like the two commented lines. How, though, can I get my randomly chosen mappings2 to be used when eval-ing both strings, if I cannot pass it as an argument in the re.sub callback function?

非常感谢。

推荐答案

我猜最简单的方法是利用 functools.partial ,可让您创建部分评估函数:

The easiest way I guess is to make use of functools.partial, which allows you create a "partially evaluated" function:

from functools import partial

def evaluate(match, mappings):
    return str(eval(match.group(0)[2:-1], mappings))

mappings = {'A': 1, 'B': 2}  # Or whatever ...

newstring = sub(r'\#\{([^#]+)\}', partial(evaluate, mappings=mappings), string)

这篇关于如何将变量传递给re.sub回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆