【问题标题】:Replacing a word or words in a sentence by word or words given by user用用户给出的单词或单词替换句子中的单词或单词
【发布时间】:2023-04-06 14:51:01
【问题描述】:

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

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”。

【问题讨论】:

  • 您希望对出现多次的单词产生什么影响?请在问题中添加您观察到的和预期的输出。
  • 请张贴您的程序输出和输入逐字
  • 我观察到的输出在发布的图像中。至于我想看到的输出,如果输入的两个新词是 DOG 和 DUCK,就像它在图像中一样,我希望它产生“DOG 动词过去 DUCK”
  • 在问题正文中提供示例输入和预期输出。另外,请记住,虽然发布图片可能您更容易,但它对读者没有那么有帮助,尤其是因为他们需要点击链接为了看到结果(尽管这可能会很快被编辑)。您应该只复制和粘贴相关的控制台命令和输出,将它们格式化为代码块。

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


【解决方案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()

【讨论】:

  • 我输入了这段代码,结果是“鸭子动词过去的名词”
  • 您确定按原样使用它吗?
  • @BrandonLeeOrnelas 如果这个答案对你有帮助,请考虑accepting it
  • @BrandonLeeOrnelas 支持/接受,因为它也可能对其他人有所帮助。
【解决方案2】:
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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2020-04-16
    相关资源
    最近更新 更多