在NLP中使用tf-idf如何在python中查找语料库(包含大量文档)中特定单词的频率

问题描述 投票:1回答:1

如何使用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')
python nlp tf-idf n-gram countvectorizer
1个回答
0
投票

你的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()}
© www.soinside.com 2019 - 2024. All rights reserved.