Python字符串替换方法替换单词的多个实例

2024-09-29 01:31:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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方法)。如何替换多个单词?你知道吗


Tags: intransfor单词replacejultranslatelist
2条回答
mystring = 'this is my table pen is on the table '

trans_table = {'this':'that' , 'is':'was' , 'table':'chair'}

final_string = ''

words = mystring.split()

for word in words:
  if word in trans_table:
    new_word = trans_table[word]
    final_string = final_string + new_word + ' '
  else:    
    final_string = final_string + word + ' '

print('Original String :', mystring)
print('Final String :' , final_string)

在for循环耗尽后,需要将替换的结果赋回sent,然后返回sent

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:
                sent = sent.replace(word, i)
    return sent

translate('xmas greeting: god jul och gott nytt år') 
# 'xmas greeting: merry christmas and happy new year'

相关问题 更多 >