-2

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.

Rahul Kumar
  • 119
  • 1
  • 8
  • 4
    I won't upvote nor downvote, but members of the community will certainly ask you to show what have you have tried so far. – Haroldo_OK Dec 14 '20 at 10:05
  • 2
    Do you just want to replace the strings `'temp'` and `'humidity'` by the numbers `23` and `12`, or do you also want to evaluate the resulting string `'3 + 2 * 23 + 12'` as an arithmetic expression to get the number 61? – mkrieger1 Dec 14 '20 at 10:13
  • 1
    BTW, you may want to take a look at this similar (but more complex) question: https://stackoverflow.com/questions/57744290/parse-a-list-of-expressions-using-pyparsing – Haroldo_OK Dec 14 '20 at 17:23

2 Answers2

2

You could just use a regex to look for the variables, and use re.sub to replace each matched variable by its value:

import re

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

def replace_var(m):
    return str(environment[m.group(0)])

def replace_vars(expression):
    return re.sub(r'[a-z]+', replace_var, expression)  # assuming your variables are all lowercase

print(replace_vars(expression))
# 3 + 2 * 23 + 12

This will raise a KeyError in case a variable doesn't exist in environment.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
2

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)
trincot
  • 317,000
  • 35
  • 244
  • 286