2017-04-06 1 views
0

によって与えられた言葉で文章中の単語や語句を交換します。供給された2つの単語があった場合は、単語や私は、ユーザーが与える入力された言葉で文章中の特定の単語を置き換えるためにしようとしていたユーザ

$ python3 madlib.py 

Enter NOUN : DOG 

Enter NOUN : DUCK 

the DUCK VERB PAST the DUCK 

:端子を介して上記の実行時に

def replace(line, word): 
    new_line = '' 
    for i in range(line.count(word)): 
     new_word = input('Enter ' +word+ ' : ') 
     new_line = line.replace(word, new_word) 
    return new_line 
def main(): 
    print(replace('the noun verb past the noun', 'noun')) 

    main() 

出力:私は以下のコードとの例に見られるように、個別の単語を交換する方法を考え出すのトラブルを抱えていますDOGDUCK、私はそれが「the DOG verb past the DUCK」を生成したいと思います。

+0

あなたが複数回出現する単語で起こるために何をしたいですか?そして、あなたの観測された期待される出力を質問に加えてください。 – datell

+0

プログラムの出力を投稿し、_verbatim_を入力してください。 –

+1

私の観測された出力は画像に掲載されています。私の知る限り、2つの新しい単語が入力されているかどうかを確認したい出力としてDOGしており、それが好きDUCKは私がサンプル入力を –

答えて

1

、行われなければ、このような何か必要があるあなたが交換回数を渡すためにreplace()maxreplace(第三引数)を使用することができます。これはになります

def replace_word(line, word): 
    new_line = line  
    for i in range(line.count(word)): 
     new_word = input('Enter ' +word+ ' : ') 
     new_line = new_line.replace(word, new_word, 1) # replacing only one match 
    return new_line 
def main(): 
    print(replace_word('the noun verb past the noun', 'noun')) 

main() 

を:

>>> Enter noun : dog 
>>> Enter noun : duck 
>>> the dog verb past the duck 

あなたが参照することができます理解を深めるためthis documentationにしてください。

注:これは、すでにPythonインタプリタによって識別されたカスタム関数の名前を使用することをお勧めではありません。したがって、関数replace()の代わりにreplace_word()などを使用してください。

+0

私はこのコードを入力し、結果: –

+0

私はこのコードを入力し、出力は "名詞の後のダック動詞"でした –

+0

あなたはそれをそのまま使用していますか? –

0
def replace(line, word): 
    new_line = line 
    for i in range(line.count(word)): 
     new_word = input('Enter ' +word+ ' : ') 
     start_index = new_line.find(word) #returns the starting index of the word 
     new_line = new_line[:start_index] + new_word + new_line[start_index + len(word):] 
    return new_line 
def main(): 
    print(replace('the noun verb past the noun', 'noun')) 
main() 
関連する問題