用python实现一个基于面向对象思想的,具有背单词、添加新单词、删除单词、查找单词、以及清空、退出单词本功能的生词本程序
时间: 2023-07-10 12:39:48 浏览: 120
好的,我可以为您提供一个简单的代码示例:
```python
class Vocabulary:
def __init__(self):
self.words = {}
def add_word(self, word, definition):
self.words[word] = definition
print(f"Added '{word}' to vocabulary.")
def delete_word(self, word):
if word in self.words:
del self.words[word]
print(f"Deleted '{word}' from vocabulary.")
else:
print(f"'{word}' not found in vocabulary.")
def search_word(self, word):
if word in self.words:
print(f"'{word}': {self.words[word]}")
else:
print(f"'{word}' not found in vocabulary.")
def clear_all(self):
self.words.clear()
print("Cleared all words from vocabulary.")
def display_menu(self):
print("\nVOCABULARY MENU")
print("1. Add word")
print("2. Delete word")
print("3. Search word")
print("4. Clear all words")
print("5. Quit")
def run(self):
while True:
self.display_menu()
choice = input("Enter your choice: ")
if choice == "1":
word = input("Enter word to add: ")
definition = input("Enter definition: ")
self.add_word(word, definition)
elif choice == "2":
word = input("Enter word to delete: ")
self.delete_word(word)
elif choice == "3":
word = input("Enter word to search: ")
self.search_word(word)
elif choice == "4":
self.clear_all()
elif choice == "5":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == '__main__':
vocabulary = Vocabulary()
vocabulary.run()
```
这个程序定义了一个名为`Vocabulary`的类,包含了添加、删除、查找和清空单词的方法。在`run`方法中,使用一个无限循环来显示菜单和接收用户的选择,直到用户选择退出为止。
阅读全文