如何从文档项矩阵中提取单词频率?

Aeg*_* Wu 0 python dictionary text-mining

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

corpus = [dictionary.doc2bow(text) for text in texts].
Run Code Online (Sandbox Code Playgroud)

是否有任何简单的方法可以计算整个语料库中的单词频率.由于我的词典是term-id列表,我想我可以将词频与term-id匹配.

tit*_*ata 5

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

from nltk import FreqDist
import nltk
texts = 'hi there hello there'
words = nltk.tokenize.word_tokenize(texts)
fdist = FreqDist(words)
Run Code Online (Sandbox Code Playgroud)

fdist会给你给定字符串的单词频率texts.

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

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)