Find and replace characters in a string from a list
I have two types like this:
in_dict = {
'1': 'active_rate',
'2': 'purchase_per_active'
}
formula = {
'total_purchase': 'B1*B2'
}
I need to find the integers in a formula
dict value 'B1*B2'
and then get the integer value corresponding to the integers from the dictionary in_dict
and finally replace B1
with active_rate
and B2
with purchase_per_active
.
- STEP 1: Extract numbers from
formula
dict. for example['1','2']
in our case. - STEP 2: find the keys in the
in_dict
dict and get the corresponding values. - STEP 3: Replace the
formula
dict with the values generated in STEP 2.
So the final formula
dict should be like
formula = {
'total_purchase': 'active_rate*purchase_per_active'
}
Code while
for key, value in formula.items():
numbers = re.findall("\d+", value) # ['1','2']
values = [in_dict.get(num) for num in numbers] # ['active_rate', 'purchase_per_active']
Now how to replace 'B1'
with 'active_rate'
and 'B2'
with 'purchase_per_active'
?
The example shown here is for reference only. The nature of the code should be general.
source to share
You can use regex substitution by using a function to directly search for each of the parameters:
import re
in_dict = {
'1': 'active_rate',
'2': 'purchase_per_active'
}
formula = {
'total_purchase': 'B1*B2'
}
def lookup(number):
return in_dict[number.group(1)]
for key, value in formula.items():
formula[key] = re.sub("[a-zA-Z](\d+)", lookup, value)
print formula
This gives the following output:
{'total_purchase': 'active_rate * purchase_per_active'}
It might make sense to me if in_dict
keys like "B1", "C1" are stored.
import re
in_dict = {
'A1': 'active_rate1',
'A2': 'purchase_per_active1',
'B1': 'active_rate2',
'B2': 'purchase_per_active2'
}
formula = {
'total_purchase': 'B1*B2',
'total_purchase2': 'A1*A2'
}
def lookup(cell):
return in_dict[cell.group(1)]
for key, value in formula.items():
formula[key] = re.sub("([a-zA-Z]\d+)", lookup, value)
print formula
{'total_purchase2': 'active_rate1 * purchase_per_active1', 'total_purchase': 'active_rate2 * purchase_per_active2'}
source to share