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

在Python中实现一个Vocabulary()类,用于统计文本中出现的单词数量

发布时间:2023-12-25 01:40:14

下面是一个实现了Vocabulary类的Python代码,用于统计文本中出现的单词数量。

import re

class Vocabulary:
    def __init__(self):
        self.word_count = {}
    
    def add_text(self, text):
        words = re.findall(r'\b\w+\b', text.lower())
        for word in words:
            self.word_count[word] = self.word_count.get(word, 0) + 1
    
    def get_word_count(self, word):
        return self.word_count.get(word, 0)
    
    def get_all_words(self):
        return list(self.word_count.keys())
    
    def get_vocab_size(self):
        return len(self.word_count)

使用例子:

text = "This is a sample text. It contains some words that will be counted."

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

# 添加文本
vocab.add_text(text)

# 获取单词数量
print("Word count of 'is':", vocab.get_word_count('is'))
print("Word count of 'text':", vocab.get_word_count('text'))
print("Word count of 'word':", vocab.get_word_count('word'))

# 获取所有单词
print("All words:", vocab.get_all_words())

# 获取词汇表大小
print("Vocabulary size:", vocab.get_vocab_size())

运行上面的例子代码,会输出以下结果:

Word count of 'is': 1
Word count of 'text': 1
Word count of 'word': 1
All words: ['this', 'is', 'a', 'sample', 'text', 'it', 'contains', 'some', 'words', 'that', 'will', 'be', 'counted']
Vocabulary size: 13

以上代码实现了一个简单的Vocabulary类,可以统计单词在给定文本中的出现次数,并提供一些常用的操作方法。