a=0.77 ,b=0.2 ,c=0.20, d=0.79 ,z=(c+d), e=(z*a) ,output=(z+e)
I have a text file like above. I need a parser logic that will throw an equation like
output=(0.20+0.79)+((0.20+0.79)*a) what are some efficient ways to do it? Are there any libraries? Thank you!
Primitive method is to work with strings and use replace()
First use split(',')
to convert string to list
['a=0.77 ', 'b=0.2 ', 'c=0.20', ' d=0.79 ', 'z=(c+d)', ' e=(z*a) ', 'output=(z+e)']
Next use .strip()
to remove spaces from ends and begins.
Next use .split('=')
on every element to create nested lists.
[['a', '0.77'], ['b', '0.2'], ['c', '0.20'], ['d', '0.79'], ['z', '(c+d)'], ['e', '(z*a)'], ['output', '(z+e)']]
Next use dict()
to create dictionary.
{'a': '0.77','b': '0.2','c': '0.20','d': '0.79','e': '(z*a)','output': '(z+e)','z': '(c+d)'}
And now you can get first 'a' : '0.77
to run .replace('a', '0.77
)` on other items in dictionary. And repeate it with other values from dictionary.
So finally you could get dictionary
{'a': '0.77','b': '0.2','c': '0.20','d': '0.79','e': '((0.20+0.79)*0.77)','output': '((0.20+0.79)+((0.20+0.79)*0.77))','z': '(0.20+0.79)'}
and output
has string ((0.20+0.79)+((0.20+0.79)*0.77))
import sympy
import pprinttext = 'a=0.77 ,b=0.2 ,c=0.20, d=0.79 ,z=(c+d), e=(z*a) ,output=(z+e)'parts = text.split(',') # create list
#print(parts)
parts = [item.strip() for item in parts] # remove spaces
#print(parts)
parts = [item.split('=') for item in parts] # create tuples
#print(parts)
parts = dict(parts) # create dict
#print(parts)pprint.pprint(parts)for key1, val1 in parts.items():for key2, val2 in parts.items():parts[key2] = parts[key2].replace(key1, val1)pprint.pprint(parts)print('output:', parts['output'])