2017-03-11 8 views
1
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' 

文字列を取り込む関数を作成しようとしていますが、辞書の値と一致する単語を対応するキーに置き換えようとしています。私は1つの単語を置き換えることができるので、本当にイライラしています(replaceメソッドを使用)。複数の単語をどのように置き換えることができますか?Pythonの文字列置換メソッド - 単語の複数のインスタンスを置換する

+1

あなた 'あなたの最初のマッチの機能からreturn'。これは 'for'ループと関数から完全に抜け出します。現在のアプローチでは、 'return'を使う前に文全体を再構築する必要があります。 – roganjosh

+0

それはよく説明された、ありがとう – Paulos

答えて

3

あなたは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' 
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)