请你用python,仿照学生信息管理系统,写一个唐诗管理系统,从txt文件读取唐诗,定义一个唐诗类,和方法类,包含列出所有唐诗的名字、添加一首唐诗、删除一首唐诗,根据诗名查找唐诗、退出程序这些功能,并给出注释、
时间: 2024-12-11 17:18:28 浏览: 7
好的,我们可以创建一个简单的唐诗管理系统的Python程序。首先,我们定义一个`Poem`类用于存储唐诗的信息,以及一些辅助函数来处理文件操作。这里是一个基本的设计:
```python
# poem_manager.py
import os
class Poem:
def __init__(self, title, content):
self.title = title
self.content = content
# 展示诗歌标题
def display_title(self):
print(f"标题:{self.title}")
# 显示诗歌内容
def display_content(self):
print(f"内容:\n{self.content}\n")
def read_poems_from_file(filename):
"""
从文件中读取唐诗并返回一个字典,键为诗名,值为诗的内容。
"""
poems = {}
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
if ':' in line:
title, content = line.strip().split(':')
poems[title] = content
return poems
def save_poem(poem_dict, filename):
"""
将诗歌保存到文件中,格式为:诗名: 诗句。
"""
with open(filename, 'w', encoding='utf-8') as file:
for title, content in poem_dict.items():
file.write(f"{title}: {content}\n")
def manage_poems():
# 初始化数据
poem_file = "poems.txt"
all_poems = read_poems_from_file(poem_file)
while True:
print("\n1. 列出诗歌\n2. 添加诗歌\n3. 删除诗歌\n4. 查找诗歌\n5. 退出")
choice = input("请输入您的选择:")
if choice == '1':
for title, _ in all_poems.items():
print(title)
elif choice == '2':
title = input("请输入新诗的标题:")
content = input("请输入新诗的内容:")
all_poems[title] = content
save_poem(all_poems, poem_file)
elif choice == '3':
title = input("请输入要删除的诗名:")
if title in all_poems:
del all_poems[title]
save_poem(all_poems, poem_file)
print(f"{title} 已经删除.")
else:
print("找不到该诗名.")
elif choice == '4':
search_word = input("请输入诗名查找:")
if search_word in all_poems:
poem = Poem(search_word, all_poems[search_word])
poem.display_title()
poem.display_content()
else:
print("未找到匹配的诗歌.")
elif choice == '5':
break
else:
print("无效的选择,请再试一次.")
if __name__ == "__main__":
manage_poems()
```
在这个例子中,我们将唐诗存储在名为`poems.txt`的文件中,并通过`manage_poems()`函数实现了各种操作。你可以运行这个脚本来测试它。
阅读全文