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

时间:2017-03-11 17:27:47

标签: python string

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'

我正在尝试编写一个函数,该函数将接受一个字符串替换字词,该字符匹配字典中的值与其对应的键。这真是令人沮丧,因为我只能替换一个单词(使用替换方法)。如何替换多个单词?

2 个答案:

答案 0 :(得分:3)

在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'

答案 1 :(得分:0)

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)