Reputation: 245
I am trying to replace a word i.e "sound system" with "sound_sytem" in python using dictionary. However it's not working.
Here is my code:
dictionary = {'audio system': 'audio_system'}
def replace_word(text):
return " ".join([dictionary.get(w,w) for w in text.split()])
text = "adding a little more to an audio system,improve the audio system to be better"
print(replace_word(text))
here is my output :
adding a little more to an audio system,improve the audio system to be better
Upvotes: 0
Views: 250
Reputation: 5202
Try using replace()
:
for i in dictionary:
text.replace(i,dictionary[i])
this just replaces the key with value.
Your code doesn't work because, split function by default splits by space and audio system
is split as audio
and system
.
Lets do this your way, using join:
dictionary = {'audio system': 'audio_system'}
def replace_word(text):
return [dictionary[j].join([text.split(i) for i in dictionary][0]) for j in dictionary][0]
text = "adding a little more to an audio system,improve the audio system to be better"
print(replace_word(text))
Upvotes: 2