我正在尝试使用字典在python中将单词“ sound system”替换为“ sound_sytem”。但是,它不起作用。
这是我的代码:
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))
这是我的输出:
adding a little more to an audio system,improve the audio system to be better
尝试使用replace()
:
for i in dictionary:
text.replace(i,dictionary[i])
这只是将键替换为值。您的代码不起作用,因为默认情况下,split函数按空格分割,并且audio system
被拆分为audio
和system
。