替换功能不替换文本

时间:2020-07-16 13:27:25

标签: python replace

以下代码用于疯狂的libs游戏。第一部分打开模板(待更改的单词仅写为ADJECTIVE或NOUN等),并将文本保存在新变量中。第二部分查找这些待更改单词中有多少个。问题出在第三部分,我试图将模板字更改为用户输入。尽管没有错误发生,但最后打印时arent字样完全没有改变。

import os, re

# Open a text file depending on input
# Objective completed
working_file = ""
while True:
    filename = input("Name of MADLIB template file with extension: ")
    if os.path.isfile(os.path.join(os.getcwd(), filename)):
       input_file = open(filename, "r")
       working_file = input_file.read()
       input_file.close()
       break
    else:
        print("No such file found")


# Find any instances of ADVERB, VERB, NOUN, ADJECTIVE in working_file
# Objective completed
words_regex = re.compile(r'ADVERB|VERB|NOUN|ADJECTIVE')
words_found = words_regex.findall(working_file)
print(f"The madlibs template countains {words_found}")

# TODO Replace each word type in working_file with user input before writing to text file
for word_type in words_found:
    user_input = input(f"Input an/a {word_type}: ")
    working_file.replace(word_type, user_input, 1)

print(working_file)

因此一个包含以下内容的模板疯了libs文本文件:

这只熊猫走到名词,然后是动词。附近的名词 不受这些事件的影响。

确切地是最后打印出的内容。

1 个答案:

答案 0 :(得分:1)

您应该将更改分配给更改的变量:

working_file = working_file.replace(word_type, user_input, 1)
相关问题