Python Mad Libs项目问题:用户输入无法替换占位符并保存
问题场景
用Python开发Mad Libs风格项目,收集VERB_ING、NOUN、ADJECTIVE等用户输入替换文本占位符,但运行程序后,原文件里的占位符未被替换,怀疑save_crazy_lib函数存在bug。
终端操作步骤
michaelsmacbook@Michaelss-MBP Desktop % python3 crazy.py lib.txt Enter a VERB_ING:drink Enter a NOUN:water Enter a VERB_ING:go Enter a ADJECTIVE:quickly Enter a NOUN:north Enter a VERB_ING:smiling Enter a NOUN:goth michaelsmacbook@Michaelss-MBP Desktop % cat lib.txt
原始lib.txt文本
The first thing that stands between you and VERB_ING your first,
real, piece of NOUN, is VERB_ING the skill of breaking problems down
into achievable ADJECTIVE actions that a NOUN can do for you. Of
course, you and the computer will also need to be VERB_ING a common
NOUN, but we'll get to that topic in just a bit.
完整代码
import sys def make_crazy_lib(filename): try: file = open(filename, 'r') text = '' for line in file: text = text + process_line(line) file.close() return text except FileNotFoundError: print("Sorry, cound't find" + filename + '.') except IsADirectoryError: print("Sorry", filename, 'is a directory.') except: print("Sorry, could not read", filename) placeholders = ['NOUN', 'ADJECTIVE', 'VERB_ING','VERB'] def process_line(line): global placeholders processed_line = '' words = line.split() for word in words: stripped = word.strip('.,:?!') if stripped in placeholders: answer = input('Enter a ' + stripped + ":") processed_line = processed_line + answer if word[-1] in '.,;?!': processed_line = processed_line + word[-1] + ' ' else: processed_line = processed_line + ' ' else: processed_line = processed_line + word + ' ' return processed_line + '\n' def save_crazy_lib(filename, text): #This may be where the issue is try: file = open(filename, "w") file.write(text) file.close() except: print("Sorry, couldn't write file." + filename, lib) def main(): if len(sys.argv) != 2: print("crazy.py<filename>") else: filename = sys.argv[1] lib = make_crazy_lib(filename) if (lib != None): save_crazy_lib('crazy' + filename, lib) if __name__ == '__main__': main()
问题分析与修复
核心误解:保存路径错误
代码中main函数调用save_crazy_lib时,传入的文件名是'crazy' + filename,也就是输入lib.txt时,替换后的内容会保存到crazylib.txt,而非原lib.txt。你运行cat lib.txt查看的是未修改的原文件,自然看不到替换结果。save_crazy_lib函数的异常处理bug
异常提示中使用了未定义的变量lib,修正后的函数如下:def save_crazy_lib(filename, text): try: file = open(filename, "w") file.write(text) file.close() except Exception as e: print(f"Sorry, couldn't write file {filename}: {e}")可选:覆盖原文件
如果需要直接替换原文件内容,将main函数中的调用改为:save_crazy_lib(filename, lib)其他小问题修正
make_crazy_lib函数中的拼写错误:cound't改为couldn't。
验证方法
- 若保留原保存路径,运行程序后查看
crazylib.txt即可看到替换后的内容; - 若修改为覆盖原文件,直接运行
cat lib.txt就能验证结果。
内容的提问来源于stack exchange,提问作者Michael Agunga

