欢迎访问宙启技术站
智能推送

在Python中实现一个Vocabulary()类,用于存储和查询单词的中文翻译

发布时间:2023-12-25 01:39:47

下面是一个简单的实现Vocabulary类的示例代码:

class Vocabulary:
    def __init__(self):
        self.words = {}

    def add_word(self, word, translation):
        self.words[word] = translation

    def get_translation(self, word):
        return self.words.get(word, "Word not found in the vocabulary.")

# 创建一个Vocabulary对象
vocab = Vocabulary()

# 添加单词和翻译
vocab.add_word("apple", "苹果")
vocab.add_word("banana", "香蕉")
vocab.add_word("cat", "猫")

# 查询单词的翻译
print(vocab.get_translation("apple"))  # 输出:苹果
print(vocab.get_translation("dog"))    # 输出:Word not found in the vocabulary.

在上面的示例中,我们首先创建了一个Vocabulary类,并初始化了一个空的words字典来存储单词和翻译。然后,我们定义了两个方法:add_word用于添加单词和翻译到words字典中,get_translation用于查询单词的翻译。

在主程序中,我们创建了一个Vocabulary对象,并使用add_word方法添加了几个单词和对应的翻译。然后,我们使用get_translation方法查询了两个单词的翻译,并将结果打印出来。

希望这个例子能够帮助你理解如何在Python中实现一个Vocabulary类。请记住,这只是一个简单的示例,你可以根据自己的需求添加更多的方法和功能。