如何从文档术语矩阵中提取词频?
How to extract word frequency from document-term matrix?
我正在使用 Python 进行 LDA 分析。我使用以下代码创建了一个文档术语矩阵
corpus = [dictionary.doc2bow(text) for text in texts].
有什么简单的方法可以计算整个语料库的词频。由于我确实有字典,它是一个术语 ID 列表,我想我可以将词频与术语 ID 匹配。
您可以使用 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-learn
中的 CountVectorizer
作为字符串列表。
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
我正在使用 Python 进行 LDA 分析。我使用以下代码创建了一个文档术语矩阵
corpus = [dictionary.doc2bow(text) for text in texts].
有什么简单的方法可以计算整个语料库的词频。由于我确实有字典,它是一个术语 ID 列表,我想我可以将词频与术语 ID 匹配。
您可以使用 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-learn
中的 CountVectorizer
作为字符串列表。
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