Home > Software design >  How to replace specific parts of string contain numbers with a matching dictionary?
How to replace specific parts of string contain numbers with a matching dictionary?

Time:10-27

I would like to replace specific parts of string containing numbers with a dictionary. Suppose I have a dictionary:

d = {7: 'mandat_dépôt', 46: 'battu', 79: 'alphabétisé', 127: 'escrime', 160: 'daara', 162: 'arrivée_foyer', 169: 'fugue', 170: 'né_légitimement'}

I have these kinds of string:

s_1 = "7 ==> 127 #SUP: 41 #CONF: 0.8723404255319149"
s_2 = "46 ==> 162,169 #SUP: 39 #CONF: 0.8478260869565217"
s_3 = "46,169 ==> 162 #SUP: 39 #CONF: 0.975"
s_4 = "160,169 ==> 79,162 #SUP: 40 #CONF: 0.7692307692307693"
s_5 = "160,162,170 ==> 79 #SUP: 39 #CONF: 0.8125"

Expected strings:

new_s_1 = "mandat_dépôt ==> escrime #SUP: 41 #CONF: 0.8723404255319149"
new_s_2 = "battu ==> arrivée_foyer,fugue #SUP: 39 #CONF: 0.8478260869565217"
new_s_3 = "battu,fugue ==> arrivée_foyer #SUP: 39 #CONF: 0.975"
new_s_4 = "daara,fugue ==> alphabétisé,arrivée_foyer #SUP: 40 #CONF: 0.7692307692307693"
new_s_5 = "daara,arrivée_foyer,né_légitimement ==> alphabétisé #SUP: 39 #CONF: 0.8125"

Note that i don't want to replace the value of #SUP even if there exists some keys in the the dictionary.

Is there an effective way to do it?

CodePudding user response:

1- split the string by " "
2- loop over them and check which ones is an instance of your dict; if True replace with
3- join the string back by " " If there are keys you want to exclude, you will need to add additional check for them.

Example code

d = {7: 'mandat_dépôt', 46: 'battu', 79: 'alphabétisé', 127: 'escrime', 160: 'daara', 162: 'arrivée_foyer', 169: 'fugue', 170: 'né_légitimement'}

s_1 = "7 ==> 127 #SUP: 41 #CONF: 0.8723404255319149"


n_1 = " ".join([d.get(int(ni)) if ni.isnumeric() and d.get(int(ni))  else ni for ni in s_1.split(" ") ])
print(n_1)

CodePudding user response:

effective way to do it is with list or dictionaries:

With Lists:

old_s = [s_1, s_2, s_3, s_4, s_5]
new_s = []

for i in old_s:
    number, string = i.split('==>')
    new_s.append(f"{','.join([d[int(j)] for j in number.split(',')])} ==> {string}")

for i in new_s:
    print(i)

With Dictionaries:

old_s = dict(s_1=s_1, s_2=s_2, s_3=s_3, s_4=s_4, s_5=s_5)
new_s = dict()

for k, v in old_s.items():
    print(f"{k} = {v}")
    number, string = v.split('==>')
    new_s[f"new_{k}"] = f"{','.join([d[int(j)] for j in number.split(',')])} ==> {string}"

for k, v in new_s.items():
    print(f"{k} = {v}")

I hope that helps you. Good luck.

  • Related