使用Python编写一个Vocabulary()类,实现基本的单词添加和删除功能
发布时间:2023-12-25 01:40:01
下面是一个使用Python编写的Vocabulary()类的示例代码,实现了基本的单词添加和删除功能:
class Vocabulary:
def __init__(self):
self.words = []
def add_word(self, word):
if word not in self.words:
self.words.append(word)
return True
else:
return False
def remove_word(self, word):
if word in self.words:
self.words.remove(word)
return True
else:
return False
使用例子:
# 创建一个Vocabulary对象
vocab = Vocabulary()
# 添加单词
vocab.add_word("apple") # 返回True
vocab.add_word("banana") # 返回True
vocab.add_word("apple") # 返回False,因为"apple"已经存在于词汇表中
# 获取当前词汇表中的单词
print(vocab.words) # 输出:['apple', 'banana']
# 删除单词
vocab.remove_word("apple") # 返回True
vocab.remove_word("orange") # 返回False,因为"orange"不存在于词汇表中
# 获取当前词汇表中的单词
print(vocab.words) # 输出:['banana']
在上面的例子中,我们首先创建了一个Vocabulary对象(vocab),然后使用add_word()方法向词汇表中添加了几个单词。最后,我们使用remove_word()方法从词汇表中删除了一个单词。通过打印vocab.words,我们可以看到词汇表中的单词列表。
注意,Vocabulary类的实现中没有涉及词汇表的持久化保存。如果希望在程序重启后仍然保留词汇表中的单词,可以考虑使用文件或数据库进行存储。
