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

ihm*_*all 4 python data-science

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

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

例子:

File 1 - "aaa", "xyz", "cccc", "dddd", "aaa"  
File 2 - "abc", "aaa"
Corpus - "aaa", "abc", "cccc", "dddd", "xyz"  
Run Code Online (Sandbox Code Playgroud)

输出矩阵:

[[2, 0, 1, 1, 1],
 [1, 1, 0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)

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

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

Igo*_*ush 5

下面是一个相当简单的解决方案,它使用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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)

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

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