【发布时间】:2021-08-16 11:50:53
【问题描述】:
关于我的问题 Replace word, but another word with same letter format got replaced
def slangwords(kalimat):
replacements = {
'sweets': 'candy',
'sweetmeat': 'candy',
'jawbreaker': 'candy'
}
words = kalimat.split(' ')
for i, word in enumerate(words):
words[i] = replacements.get(word, word)
return " ".join(words)
有没有我可以替换超过 1 个具有相同含义的单词而不用 1 加 1。所需的输出是这样实现的,只是输入所有这些糖果表示效率不高
'sweets': 'candy',
'sweetmeat': 'candy',
'jawbreaker': 'candy'
【问题讨论】:
-
你想改哪些字,请说明你想做什么?
-
请同时添加您的示例输入和预期输出。
-
使用理解
" ".join(replacements.get(word, word) for word in words) -
您可以随心所欲地存储它,但为了替换,您需要以您当前拥有的格式进行处理。
-
@TimRoberts 好的,所以如果不输入所有这些糖果表示,我就无法做到这一点,对吧?
'sweets':**candy**