Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to replace some variables in a file from another file, I want only that particular variable to be replaced but not part of another variable too.


file1="0=0.49,1=0.50,2=0.12,3=0.87,4=0.88,5=0.11"
file2="((((2*(v-2))+(3*(v2)))*(0*(v-1)))+(((4*(v-2))+(5*(v2)))*(1*(v1))))"

Current result :((((0.12*(v-0.12))+(0.87*(v0.12)))*(0.49*(v-0.50)))+(((0.88*(v-0.12))+(0.11*(v0.12)))*(0.50*(v0.50))))

Desired result :((((0.12*(v-2))+(0.87*(v2)))*(0.49*(v-1)))+(((0.88*(v-2))+(0.11*(v2)))*(0.50*(v1))))

What I have tried:

file1="0=0.49,1=0.50,2=0.12,3=0.87,4=0.88,5=0.11"
file2="((((2*(v-2))+(3*(v2)))*(0*(v-1)))+(((4*(v-2))+(5*(v2)))*(1*(v1))))"

variables = {}
for equation in file1.split(","):
var, value = equation.split("=")
variables[var] = value
print(variables)
operation = [variables.get(letter, letter) for letter in file2]
op="result = " + "".join(operation)
print(op)
Posted
Updated 18-Nov-21 3:11am
v2
Comments
Richard MacCutchan 18-Nov-21 9:57am    
Once you have split file1 you need to go through the file 2 content, copying it character by character to a new array. Each time you find a number followed by asterisk, you copy the value form the variables dictionary instead of the digit.

1 solution

If your inputs maintain the regularity of file2 then you should match the digits surrounded by (* (e.g. (2*), and replace only such digits with the variable values.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900