如何用另一个单词替换文本中的某些单词

问题描述 投票:0回答:1

我正在尝试使用字典在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
python str-replace
1个回答
2
投票

尝试使用replace()

for i in dictionary:
    text.replace(i,dictionary[i])

这只是将键替换为值。您的代码不起作用,因为默认情况下,split函数按空格分割,并且audio system被拆分为audiosystem

© www.soinside.com 2019 - 2024. All rights reserved.