简体   繁体   中英

How to replace some words in a text with another word

I am trying to replace a word ie "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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM