I have a mapping as a dict
{
'a': ['a1','a2','a3'],
'b': ['b1', 'b2'],
'c': ['c1', 'c2', 'c3', 'c4]
}
Given a sentence, all occurrences of 'a1', 'a2', 'a3' should be replaced with 'a', similarly all occurrences of 'b1', 'b2' should be replaced with 'b'. How can this be done efficiently? This is the current code:
def word_replacer(text):
s = {
'a': ['a1','a2','a3'],
'b': ['b1', 'b2'],
'c': ['c1', 'c2', 'c3', 'c4']
}
words = text.split(" ")
for idx, word in enumerate(words):
changed_word=[k for k, v in s.items() if word in [vals.lower() for vals in v]]
if ((len(changed_word)>0) and (word != changed_word[0])):
words[idx] = changed_word[0]
result = " ".join(words)
return result