用一个或多个用户给出的单词替换一个或多个单词

时间:2017-04-06 21:56:11

标签: python string python-3.x replace user-input

我试图用一个用户给出的输入单词替换句子中的给定单词。我无法弄清楚如何单独替换单词,如下面的代码和示例所示:

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

通过终端运行上述内容时的输出:

$ python3 madlib.py

Enter NOUN : DOG

Enter NOUN : DUCK

the DUCK VERB PAST the DUCK

如果提供的两个单词是DOGDUCK,我希望它能生成“the DOG verb past the DUCK”。

2 个答案:

答案 0 :(得分: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_word()或类似的内容,而不要命名您的函数replace()

答案 1 :(得分: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()