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

标签 python nlp tf-idf n-gram countvectorizer

如何使用 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()}

关于python - 在 NLP 中使用 tf-idf 如何从 python 中的语料库(包含大量文档)中查找特定单词的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55626246/

相关文章:

python - 使用 Redis 进行批量插入失败并出现奇怪的错误

web-services - 自动文本翻译

python - Python 中的 TF-IDF 实现

bayesian - 如何用朴素贝叶斯实现 TF_IDF 特征加权

solr - 我如何根据 tf-idf 分数而不是受欢迎程度对构面进行排序?

python - 使用 sys 或 fileinput 库从 python 中的标准输入读取是否更有效?

python - 使用 np.where 根据条件在 pandas df 中创建一个新列

python - 在 spacy 的帮助下合并几乎相似的行

python - 按数字顺序遍历字典中的文件

python - 值错误 : operands could not be broadcast together with shapes in Naive bayes classifier