Python 替换函数不替换文本
下面的代码是一个疯狂的libs游戏。第一部分打开模板(要更改的单词只写为形容词或名词等),并将文本保存在新变量中。第二部分找出其中有多少要更改的单词。问题在第三部分,我试图将模板词更改为用户输入。虽然没有出现错误,但在最后打印时,这些文字根本没有更改Python 替换函数不替换文本,python,replace,Python,Replace,下面的代码是一个疯狂的libs游戏。第一部分打开模板(要更改的单词只写为形容词或名词等),并将文本保存在新变量中。第二部分找出其中有多少要更改的单词。问题在第三部分,我试图将模板词更改为用户输入。虽然没有出现错误,但在最后打印时,这些文字根本没有更改 import os, re # Open a text file depending on input # Objective completed working_file = "" while True: filen
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)
因此,模板mad libs文本文件包含:
形容词panda依次指向名词和动词。邻近名词
没有受到这些事件的影响
正是最后打印出来的内容。您应该将更改分配给已更改的变量:
working_file = working_file.replace(word_type, user_input, 1)
您必须将替换结果分配回
工作\u文件
。目前,替换正在工作,但您正在丢弃结果。str.replace
没有替换到位,因此您必须执行working\u file=working\u file.replace(word\u类型,用户输入,1)