使用Python编写一个Vocabulary()类,实现单词的导入和导出功能
发布时间:2023-12-25 01:43:27
以下是一个使用Python编写的Vocabulary()类,实现单词的导入和导出功能,并附带使用例子。
import json
class Vocabulary:
def __init__(self):
self.words = {}
def import_words(self, file_name):
try:
with open(file_name, 'r') as file:
self.words = json.load(file)
except FileNotFoundError:
print("File not found.")
def export_words(self, file_name):
with open(file_name, 'w') as file:
json.dump(self.words, file)
def add_word(self, word, definition):
self.words[word] = definition
def remove_word(self, word):
if word in self.words:
del self.words[word]
else:
print("Word not found.")
def search_word(self, word):
if word in self.words:
print(f"{word}: {self.words[word]}")
else:
print("Word not found.")
def display_words(self):
if len(self.words) == 0:
print("No words in the vocabulary.")
else:
for word, definition in self.words.items():
print(f"{word}: {definition}")
# 使用例子
vocabulary = Vocabulary()
# 导入单词
vocabulary.import_words("words.json")
# 添加单词
vocabulary.add_word("apple", "a round fruit with red or green skin and firm white flesh")
vocabulary.add_word("book", "a written or printed work consisting of pages glued or sewn together along one side and bound in covers")
vocabulary.add_word("cat", "a small domesticated carnivorous mammal with soft fur, a short snout, and retractile claws")
# 导出单词
vocabulary.export_words("words.json")
# 删除单词
vocabulary.remove_word("apple")
# 搜索单词
vocabulary.search_word("book")
# 显示所有单词
vocabulary.display_words()
在上面的例子中,我们首先创建了一个Vocabulary()类的实例。然后使用import_words()方法从文件中导入单词列表。接着使用add_word()方法添加一些新的单词。然后使用export_words()方法将新的单词列表导出到文件中。之后,我们使用remove_word()方法删除了一个单词。然后使用search_word()方法搜索了一个单词。最后,使用display_words()方法显示了所有单词和它们的定义。
注意:在使用上述代码之前,需要确保words.json文件存在,并且包含正确的JSON格式。
