def translate(sent):
trans={"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
word_list = sent.split(' ')
for word in word_list:
for i,j in trans.items():
if j == word:
return sent.replace(word, i)
>>>translate('xmas greeting: god jul och gott nytt år')
'xmas greeting: merry jul och gott nytt år'
我正在尝试编写一个函数,它将接受一个字符串,并用相应的键替换与字典中的值匹配的单词。这真的很令人沮丧,因为我只能替换一个单词(使用replace方法)。如何替换多个单词?你知道吗
在for循环耗尽后,需要将替换的结果赋回
sent
,然后返回sent
:相关问题 更多 >
编程相关推荐