【问题标题】:How to extract word frequency from document-term matrix?如何从文档术语矩阵中提取词频?
【发布时间】:2016-07-30 03:10:25
【问题描述】:

我正在使用 Python 进行 LDA 分析。我使用以下代码创建了一个文档术语矩阵

corpus = [dictionary.doc2bow(text) for text in texts].

有没有简单的方法来计算整个语料库的词频。由于我确实有字典,它是一个 term-id 列表,我想我可以将词频与 term-id 匹配。

【问题讨论】:

标签: python dictionary text-mining


【解决方案1】:

您可以使用nltk 来计算字符串texts 中的词频

from nltk import FreqDist
import nltk
texts = 'hi there hello there'
words = nltk.tokenize.word_tokenize(texts)
fdist = FreqDist(words)

fdist 将为您提供给定字符串texts 的词频。

但是,您有一个文本列表。一种计算频率的方法是使用来自scikit-learnCountVectorizer 作为字符串列表。

import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
texts = ['hi there', 'hello there', 'hello here you are']
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
freq = np.ravel(X.sum(axis=0)) # sum each columns to get total counts for each word

这个freq将对应字典vectorizer.vocabulary_中的值

import operator
# get vocabulary keys, sorted by value
vocab = [v[0] for v in sorted(vectorizer.vocabulary_.items(), key=operator.itemgetter(1))]
fdist = dict(zip(vocab, freq)) # return same format as nltk

【讨论】:

  • 谢谢。但问题是我的文本不仅仅是一份文件。它似乎是一个列表,我有 texts[1], texts[2]....
  • @AegeanT.Wu,如果您有文本列表,我更新了答案
  • 词汇已排序,但频率没有,这还可以吗?
  • @learn2day,是的,没关系。我只对 scikit learn 的词汇输出进行排序,使其与 freq 数组对齐。您可以再次按其值对输出的fdist 字典进行排序,以便按频率排序。
  • 您可以使用OrderedDict按值排序,即OrderedDict(sorted(fdist.items(), key=operator.itemgetter(1)))
猜你喜欢
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 2015-05-19
相关资源
最近更新 更多