用列表中的值替换字符串中的变量名,并避免重复替换 [英] replacing variable names in string with values from list and avoiding redundant replaces

查看:80
本文介绍了用列表中的值替换字符串中的变量名,并避免重复替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出eval的等式:

    eval_str = 'VAR1 > 0 and VAR1 < 10 and (VAR2 == VAR1::VALUE_X or VAR2 == VAR2::VALUE_X)'

任务:我需要用实际值替换变量(在此示例中为VAR1,VAR2),并用引号将给定的常量"(VAR1 :: VALUE_X)括起来.

Task: I need to replace variables (VAR1,VAR2 in this example), with their actual values, and also surround the given 'constant' (VAR1::VALUE_X) with quotes.

问题:由于变量名存在于常量和eval字符串中,并且由于变量可以用包含变量名本身的字符串替换-我遇到了将替换常量值中的变量名的问题通过另一个常数或变量值.显示得更好...

Problem: Since the variable name exists in the constant and in the eval string, and since the variable could replaced with a string that contains the variable name itself - I run into issues where the variable name in the constant value will be replaced by another constant or variable value. Better shown...

     eval_str = '(VAR2 == VAR2::VALUE_X or VAR2 != VAR2::VALUE_Z) and (VAR1 > 0 and VAR1 < 10)'
     var_dict = {'VAR1':'5','VAR2':'VAR1::VALUE_Y'}

     # what I do is strip out most of the special characters
     # the following findall = ['VAR1', '0', 'and', 'VAR1', '10', 'and', 'VAR2', 'VAR1::VALUE_X', 'or', 'VAR2', 'VAR2::VALUE_X']
     for x in re.findall('[^\s()<>=!]+',eval_str):
        # skip digits, and, or, None *need to improve regex
        if x.replace('.','').isdigit() or x == 'and' or x == 'or' or x == 'None':
           continue
        # if variable is in dict
        if x in var_dict.keys():
           # only replace first
           eval_str = eval_str.replace(x,var_dict[x],1) 
        # if is constant
        elif x.__contains__('::'):
           eval_str = eval_str.replace(x,'\'%s\''%x,1)

     print eval_str
     # (5::VALUE_Y == '5::VALUE_Y::VALUE_X' or VAR2 != 'VAR2::VALUE_Z') and (VAR1 > 0 and VAR1 < 10)

与其在每个变量/值中递增,不如对每个变量/变量使用正则表达式替换它们,会更好吗?还是可以解决现有的解决方案,如果每次更换后都能记住我在字符串中的位置?

Instead of incrementing through each variable/value, perhaps it would be better to replace them all using a regex for each one? Or could I fix my existing solution if there was a way to remember my position in the string after each replace?

TYVM!

推荐答案

要替换VAR1沿VAR1::VALUE_X离开,您可以使用负前瞻:

To replace VAR1 leaving along VAR1::VALUE_X you could use negative lookahead:

string = re.sub(r'VAR\d(?!\:\:)', lambda m: var_dict[m.group(0)], string)

更强大的解决方案是将字符串解析为AST并进行评估.

A more robust solution would parse the string into an AST and eval it.

这篇关于用列表中的值替换字符串中的变量名,并避免重复替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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