Python励志语录生成器开发问题:无法读取文本文件内容
励志语录生成器代码问题修复
刚学Python几天,我做了个励志语录生成器当第一个独立项目。用户输入类型(工作、健身、财务、生活),程序从对应文本文件取语录。现在只试了一种类型,但程序只停在提问阶段,读不了文件。还引入了Question.py里的Question类处理交互,但运行没预期结果,代码如下:
from Question import Question quote_type = input("What type of motivation do you need? (a) Work (b) Fitness (c) Financial (d) Life ") print(input(quote_type)) questions = [Question(quote_type[0], "")] Work_Quo = open("Work_Quotes.txt", "r") for Question in Question: answer = input(quote_type) if input == "a": import random def random_line(Work_Quo): lines = open(Work_Quo).read().splitlines() return random.choice(lines) print(random_line(Work_Quo))
代码核心问题
print(input(quote_type))完全多余,会触发无意义的二次输入,打乱程序流程。questions = [Question(quote_type[0], "")]创建了Question实例但全程未使用,属于冗余代码。Work_Quo = open("Work_Quotes.txt", "r")打开文件后未正确利用,也未关闭,会造成资源泄漏;后续random_line函数重复打开文件,逻辑混乱。for Question in Question:将类名当作可迭代对象,且循环变量与类名重名,直接引发逻辑错误。if input == "a":这里的input是内置函数,不是用户输入的变量,无法判断用户选择。import random放在分支内不符合Python规范,导入语句应放在文件开头。random_line函数定义在循环内,属于不良编码习惯,且参数名与外部变量重名,易混淆。
修复后的最简版本(无需Question类)
import random # 获取用户选择 quote_type = input("What type of motivation do you need?\n(a) Work\n(b) Fitness\n(c) Financial\n(d) Life\n\n") # 建立选项与文件的映射,方便扩展所有类型 type_to_file = { "a": "Work_Quotes.txt", "b": "Fitness_Quotes.txt", "c": "Financial_Quotes.txt", "d": "Life_Quotes.txt" } # 检查输入有效性并输出随机语录 if quote_type.lower() in type_to_file: file_path = type_to_file[quote_type.lower()] # 使用with语句自动关闭文件,避免资源泄漏 with open(file_path, "r") as f: lines = f.read().splitlines() print(random.choice(lines)) else: print("Invalid choice, please enter a, b, c or d.")
用到Question类的版本(合理利用交互类)
如果你的Question类是用来管理交互问题的,先确保Question.py的代码如下:
# Question.py class Question: def __init__(self, prompt, options): self.prompt = prompt self.options = options def get_response(self): print(self.prompt) for key, value in self.options.items(): print(f"({key}) {value}") return input("\nEnter your choice: ").lower()
主程序代码:
import random from Question import Question # 创建问题实例 motivation_question = Question( "What type of motivation do you need?", { "a": "Work", "b": "Fitness", "c": "Financial", "d": "Life" } ) # 获取用户选择 user_choice = motivation_question.get_response() # 映射到对应文件 type_to_file = { "a": "Work_Quotes.txt", "b": "Fitness_Quotes.txt", "c": "Financial_Quotes.txt", "d": "Life_Quotes.txt" } if user_choice in type_to_file: file_path = type_to_file[user_choice] with open(file_path, "r") as f: lines = f.read().splitlines() print("\n" + random.choice(lines)) else: print("\nInvalid choice, please try again.")
内容的提问来源于stack exchange,提问作者Frozenduck
相关产品推荐
相关产品推荐

