使用Python编写一个Vocabulary()类,实现单词的例句和用法展示
发布时间:2023-12-25 01:43:11
下面是一个使用Python编写的Vocabulary()类的示例,可以展示单词的例句和用法:
class Vocabulary:
def __init__(self, word):
self.word = word
self.sentences = []
def add_sentence(self, sentence):
self.sentences.append(sentence)
def show_sentences(self):
print(f"Sentences for the word '{self.word}':")
for sentence in self.sentences:
print(sentence)
def show_usage_example(self):
print(f"Usage examples for the word '{self.word}':")
for i, sentence in enumerate(self.sentences):
print(f"Example {i+1}:")
print(sentence)
# 创建一个Vocabulary对象
word = 'hello'
vocab = Vocabulary(word)
# 添加例句
vocab.add_sentence("Hello, how are you?")
vocab.add_sentence("She said hello to me.")
# 展示例句
vocab.show_sentences()
# 输出:
# Sentences for the word 'hello':
# Hello, how are you?
# She said hello to me.
# 展示用法示例
vocab.show_usage_example()
# 输出:
# Usage examples for the word 'hello':
# Example 1:
# Hello, how are you?
# Example 2:
# She said hello to me.
在这个示例中,我们创建了一个名为Vocabulary的类。在__init__方法中,我们接收一个word参数,并将其存储在self.word属性中。我们还创建了一个空列表self.sentences来存储例句。
add_sentence方法接受一个例句作为参数,并将其添加到self.sentences列表中。
show_sentences方法遍历self.sentences列表,并打印出所有例句。
show_usage_example方法类似于show_sentences方法,但它打印每个例句之前都输出一个"Example X"的标题。
在示例中,首先创建了一个名为vocab的Vocabulary对象,传入单词"hello"作为参数。然后通过add_sentence方法添加了两个例句。最后,通过调用show_sentences方法和show_usage_example方法分别展示了所有例句和用法示例。
你可以根据自己的需求扩展Vocabulary类,添加其他方法或属性来满足不同的需求。
