[英]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.我正在尝试使用字典在 python 中用“sound_sytem”替换一个单词,即“声音系统”。 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:这是我的 output:
adding a little more to an audio system,improve the audio system to be better
Try using replace()
:尝试使用
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
.您的代码不起作用,因为默认情况下拆分 function 按空间拆分,并且
audio system
拆分为audio
和system
。
Lets do this your way, using join:让我们按照自己的方式使用 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.