使用Python创建一个Vocabulary()类的实例
发布时间:2023-12-25 01:38:31
下面是一个使用Python创建一个Vocabulary()类的例子:
class Vocabulary:
def __init__(self):
self.words = []
def add_word(self, word):
if word not in self.words:
self.words.append(word)
def remove_word(self, word):
if word in self.words:
self.words.remove(word)
def get_words(self):
return self.words
# 创建一个Vocabulary类的实例
vocab = Vocabulary()
# 添加单词到实例中
vocab.add_word("apple")
vocab.add_word("banana")
vocab.add_word("carrot")
# 移除一个单词
vocab.remove_word("banana")
# 获取所有单词
words = vocab.get_words()
# 打印所有单词
for word in words:
print(word)
这个例子演示了如何创建一个Vocabulary类的实例,并利用该实例的方法来添加、移除和获取单词。在这个例子中,我们创建了一个Vocabulary类,包含一个空的words列表。通过add_word方法和remove_word方法,我们可以向Vocabulary实例中添加单词或者删除单词。最后,通过get_words方法,我们可以获取Vocabulary实例中保存的所有单词,并进行打印。
