我有一个目录中的文本文件列表。
我想创建一个矩阵,其中包含每个文件中整个语料库中每个单词的频率。 (语料库是目录中每个文件中的每个唯一单词。)
示例:
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(n = 文件数,m = 语料库中的唯一单词数)。然后,我再次遍历每个文件以查看对象中每个单词的频率,并用它填充每个列表。
有没有更好的方法来解决这个问题?也许使用 collections.Counter
单次通过?
最佳答案
下面是一个相当简单的解决方案,它使用 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}
关于python - 在 Python 中创建稀疏词矩阵(词袋),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46965524/