2017-04-06 8 views
0

문장에서 주어진 단어를 사용자가 입력 한 단어로 바꾸려고합니다. 동봉 된 단어 인 경우단어 또는 단어를 사용자가 지정한 단어 또는 단어로 교체하십시오.

$ 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"을 생산하고 싶습니다.

교체가 완료 될 같은 것을 필요로 당신은 번호를 전달하는 replace() maxreplace (세 번째 인수)를 사용할 수 있습니다
+0

두 번 이상 나타나는 단어는 어떻게하고 싶습니까? 그리고 질문에 관찰되고 기대되는 결과물을 추가하십시오. – datell

+0

프로그램 출력을 게시하고 _verbatim_을 입력하십시오. –

+1

내 관찰 결과가 게시 된 이미지에 있습니다. 내가보기를 원하는 출력은 이미지에있는 것처럼 새 단어 두 개가 DOG와 DUCK 인 경우입니다. "DUC 동사가 DUCK를지나도록"생산하고 싶습니다. –

답변

1

: 당신은 참조 할 수

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

:에

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() 

이 될 것이다 더 많은 이해를 위해 this documentation으로

참고 : 이미 파이썬 인터프리터로 식별 된 사용자 지정 함수에 이름을 사용하는 것은 좋지 않습니다. 따라서 이라는 이름을 지정하는 대신 replace_word() 또는 이와 비슷한 것을 사용하십시오.

+0

I이 코드를 입력하면 결과가 다음과 같이 나타납니다. –

+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()