使用Python编写一个简单的电子词典
发布时间:2023-12-04 17:41:15
下面是一个简单的电子词典的Python代码,包括定义词典、添加单词、查询单词、删除单词以及一个使用例子。
class Dictionary:
def __init__(self):
self.words = {}
def add_word(self, word, definition):
self.words[word] = definition
def delete_word(self, word):
if word in self.words:
del self.words[word]
print("单词'{}'删除成功。".format(word))
else:
print("单词'{}'不存在。".format(word))
def search_word(self, word):
if word in self.words:
definition = self.words[word]
print("单词: {}
解释: {}".format(word, definition))
else:
print("单词'{}'不存在。".format(word))
# 使用例子
dictionary = Dictionary()
# 添加单词
dictionary.add_word("apple", "a round fruit with red or yellow skin and firm white flesh")
dictionary.add_word("cat", "a small animal with fur, four legs, a tail, and sharp claws")
# 查询单词
dictionary.search_word("apple")
dictionary.search_word("dog")
# 删除单词
dictionary.delete_word("cat")
dictionary.delete_word("dog")
输出结果:
单词: apple 解释: a round fruit with red or yellow skin and firm white flesh 单词'dog'不存在。 单词'cat'删除成功。 单词'dog'不存在。
这个简单的电子词典实现了基本的添加、查询和删除功能。你可以根据需要修改和扩展该代码。
