Search code examples
pythonpyparsing

Parse Math Expression as "3 + 2 * temp + humidity", where replace alpha values from payload


Math Expression can be anything. The variable or alpha character here in expression are also not fixed "3 + 2 * temp + humidity". The variable must look for json and get replaced by it's value from json.

environment = {"temp": 23, "humidity": 12, "airpressure":21.12}
expression = '3 + 2 * temp + humidity'

the response I am looking is as '3 + 2 * 23 + 12'.

as I just started exploring pyparsing I couldn't find the solution.


Solution

  • You can transform the keys of your environment dictionary to a regular expression, and then replace them with the corresponding value:

    def resolve_vars(expression, environment):
        regex = r"\b({})\b".format("|".join([re.escape(k) for k in environment]))
        repl = lambda s: str(environment.get(s.group(), s.group()))
        return re.sub(regex, repl, expression)