在Python中实现一个Vocabulary()类,用于单词的分类和标记
发布时间:2023-12-25 01:41:43
以下是一个在Python中实现的Vocabulary()类,用于单词的分类和标记的示例:
class Vocabulary:
def __init__(self):
self.words = {}
def add_word(self, word, category):
if word not in self.words:
self.words[word] = category
def get_category(self, word):
if word in self.words:
return self.words[word]
else:
return None
def print_vocabulary(self):
print("==== Vocabulary ====")
for word, category in self.words.items():
print(f"{word} - {category}")
print("=====================")
# 创建一个Vocabulary对象
vocabulary = Vocabulary()
# 添加单词到词汇表
vocabulary.add_word("apple", "fruit")
vocabulary.add_word("banana", "fruit")
vocabulary.add_word("carrot", "vegetable")
vocabulary.add_word("orange", "fruit")
# 打印词汇表
vocabulary.print_vocabulary()
# 获取单词的分类
print(vocabulary.get_category("apple")) # 输出: fruit
print(vocabulary.get_category("carrot")) # 输出: vegetable
print(vocabulary.get_category("pencil")) # 输出: None
在这个示例中,我们创建了一个Vocabulary类。该类具有以下功能:
1. 构造方法__init__():初始化一个空的词汇表字典,用于存储单词和它们的分类。
2. add_word(word, category)方法:将单词和对应的分类添加到词汇表中。如果词汇表中已存在该单词,则将其分类更新为新的分类。
3. get_category(word)方法:返回给定单词的分类。如果单词在词汇表中不存在,则返回None。
4. print_vocabulary()方法:打印出当前词汇表中的所有单词和它们的分类。
使用例子中,我们创建了一个Vocabulary对象,并通过add_word()方法将几个单词和它们的分类添加到词汇表中。然后,我们通过print_vocabulary()方法打印出词汇表内容。最后,我们通过get_category()方法获取特定单词的分类。
输出结果如下:
==== Vocabulary ==== apple - fruit banana - fruit carrot - vegetable orange - fruit ===================== fruit vegetable None
这个示例只是一个简单的实现,你可以根据自己的需求对Vocabulary类进行扩展和优化。
