编写代码,实现一个基于面向对象思想的、具有背单词、添加新单词、删除单词、查找单词以及清空、退出生词本功能的生词本程序。
时间: 2023-07-10 12:28:49 浏览: 64
好的,下面是一个基于面向对象思想的生词本程序,包括背单词、添加新单词、删除单词、查找单词以及清空、退出生词本功能:
```python
class VocabularyBook:
def __init__(self):
self.words = []
def add_word(self, word):
if word not in self.words:
self.words.append(word)
print(f'添加单词 "{word}" 成功!')
else:
print(f'单词 "{word}" 已存在!')
def remove_word(self, word):
if word in self.words:
self.words.remove(word)
print(f'删除单词 "{word}" 成功!')
else:
print(f'单词 "{word}" 不存在!')
def search_word(self, word):
if word in self.words:
print(f'单词 "{word}" 存在!')
else:
print(f'单词 "{word}" 不存在!')
def clear_book(self):
self.words = []
print('生词本已清空!')
def show_book(self):
if self.words:
print('生词本:')
for word in self.words:
print(word)
else:
print('生词本为空!')
def back_word(self):
if self.words:
word = self.words[0]
self.words = self.words[1:]
print(f'背诵单词 "{word}" 成功!')
else:
print('生词本为空!')
def menu(self):
print('欢迎来到生词本!')
print('1. 添加单词')
print('2. 删除单词')
print('3. 查找单词')
print('4. 清空生词本')
print('5. 显示生词本')
print('6. 背单词')
print('7. 退出')
while True:
choice = input('请选择操作(1/2/3/4/5/6/7):')
if choice == '1':
word = input('请输入要添加的单词:')
self.add_word(word)
elif choice == '2':
word = input('请输入要删除的单词:')
self.remove_word(word)
elif choice == '3':
word = input('请输入要查找的单词:')
self.search_word(word)
elif choice == '4':
self.clear_book()
elif choice == '5':
self.show_book()
elif choice == '6':
self.back_word()
elif choice == '7':
print('退出生词本,谢谢使用!')
break
else:
print('无效的选择,请重新选择!')
if __name__ == '__main__':
book = VocabularyBook()
book.menu()
```
运行这个程序,会出现以下菜单:
```
欢迎来到生词本!
1. 添加单词
2. 删除单词
3. 查找单词
4. 清空生词本
5. 显示生词本
6. 背单词
7. 退出
请选择操作(1/2/3/4/5/6/7):
```
用户可以输入相应的数字来执行对应的操作。其中,背单词操作会从生词本中取出第一个单词并删除,表示已经背过了。