在Python中创建稀疏的单词矩阵(词袋)

时间:2017-10-26 23:57:46

标签: python data-science

我在目录中有一个文本文件列表。

我想创建一个矩阵,其中包含每个文件中整个语料库中每个单词的频率。 (语料库是目录中每个文件中的每个唯一单词。)

示例:

File 1 - "aaa", "xyz", "cccc", "dddd", "aaa"  
File 2 - "abc", "aaa"
Corpus - "aaa", "abc", "cccc", "dddd", "xyz"  

输出矩阵:

[[2, 0, 1, 1, 1],
 [1, 1, 0, 0, 0]]

我的解决方案是在每个文件上使用collections.Counter,获取包含每个单词计数的字典,并初始化并列出大小为 n × m <的列表/ em>( n =文件数, m =语料库中唯一字的数量)。然后,我再次遍历每个文件以查看对象中每个单词的频率,并用它填充每个单词。

有没有更好的方法来解决这个问题?也许在一次使用collections.Counter

1 个答案:

答案 0 :(得分:2)

以下是一个使用sklearn.feature_extraction.DictVectorizer的相当简单的解决方案。

from sklearn.feature_extraction import DictVectorizer
from collections import Counter, OrderedDict

File_1 = ('aaa', 'xyz', 'cccc', 'dddd', 'aaa')
File_2 = ('abc', 'aaa')

v = DictVectorizer()

# discover corpus and vectorize file word frequencies in a single pass
X = v.fit_transform(Counter(f) for f in (File_1, File_2))

# or, if you have a pre-defined corpus and/or would like to restrict the words you consider
# in your matrix, you can do

# Corpus = ('aaa', 'bbb', 'cccc', 'dddd', 'xyz')
# v.fit([OrderedDict.fromkeys(Corpus, 1)])
# X = v.transform(Counter(f) for f in (File_1, File_2))

# X is a sparse matrix, but you can access the A property to get a dense numpy.ndarray 
# representation
print(X)
print(X.A)
<2x5 sparse matrix of type '<type 'numpy.float64'>'
        with 6 stored elements in Compressed Sparse Row format>
array([[ 2.,  0.,  1.,  1.,  1.],
       [ 1.,  1.,  0.,  0.,  0.]])

可以通过v.vocabulary_访问从单词到索引的映射。

{'aaa': 0, 'bbb': 1, 'cccc': 2, 'dddd': 3, 'xyz': 4}