如何使用Tf-idf从语料库中找到单个单词的频率。下面是我的示例代码,现在我想打印一个单词的频率。我该如何实现?
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
corpus = ['This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?',]
X = vectorizer.fit_transform(corpus)
X
print(vectorizer.get_feature_names())
X.toarray()
vectorizer.vocabulary_.get('document')
print(vectorizer.get_feature_names())
X.toarray()
vectorizer.vocabulary_.get('document')
最佳答案
您的vectorizer.vocabulary_
具有每个单词的计数:
print(vectorizer.volcabulary_)
{'this': 8,
'is': 3,
'the': 6,
'first': 2,
'document': 1,
'second': 5,
'and': 0,
'third': 7,
'one': 4}
然后,计算单词频率很简单:
vocab = vectorizer.vocabulary_
tot = sum(vocab.values())
frequency = {vocab[w]/tot for w in vocab.keys()}