温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to create term frequency matrix for multiple text files?
list matrix python python-3.x

python - 如何为多个文本文件创建词频矩阵?

发布于 2020-04-10 16:59:55

我有以下代码,用于总共四个文本文件,每个文件都包含一些不同的关键字。它们分别称为test1.txt,test2.txt,test3.txt和test4.txt。我想将其转换为列表的矩阵/列表。我有以下代码。

temp = [''] + list(sample_collection)
values = list(sample_collection['test1.txt'])

sample_collection = [temp] + [[x] + [v.get(x, 0) for v in sample_collection.values()] for x in values]

但是,我想对其进行修改,以使其不仅包括来自test1的关键字,还包括来自其他文件的所有其他唯一关键字。我不知道该怎么做。有一段代码可以做到这一点吗?

预期输出:

[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
['apple', 1, 0, 2, 1],
['banana', 1, 1, 1, 1],
['lemon', 1, 1, 0, 0],
['grape', 0, 0, 0, 1]]

查看更多

提问者
Lana_Del_Neigh
被浏览
295
Green 2020-02-02 01:29

我会使用sklearn框架。

它不是python基本软件包的一部分,因此您需要安装它(pip install sklearn)。

比,导入CountVectorizer

from sklearn.feature_extraction.text import CountVectorizer

读取您的文件并将其存储在列表中。假设您会调用它my_corpus现在您有一个my_corpus由4个成员命名的列表

只需使用:

vectorizer =  CountVectorizer()    
matrix = vectorizer.fit_transform(my_corpus)

另外,如果您不希望使用其他水獭包,请执行以下操作:corpus = [“我喜欢狗”,“我喜欢猫”,“猫喜欢牛奶”,“您喜欢我”]
token_corpus = [s.split ()对于语料库中的s]

vocabulary = {}                                                                      
for i, f in enumerate(token_corpus):                                                 
    for t in f:                                                                      
        if t not in vocabulary:                                                      
             vocabulary[t] = [0]*len(corpus)                                         
        vocabulary[t][i]+=1                                                          

vocabulary
{'I': [1, 1, 0, 0], 'like': [1, 1, 1, 0], 'dogs': [1, 0, 0, 0], 'cats': [0, 1, 1, 0], 'milk': [0, 0, 1, 0], 'You': [0, 0, 0, 1], 'likes': [0, 0, 0, 1], 'me': [0, 0, 0, 1]}

如果要将其保存在列表中,请使用:

list(map(list, vocabulary.items()))
[['I', [1, 1, 0, 0]], ['like', [1, 1, 1, 0]], ['dogs', [1, 0, 0, 0]], ['cats', [0, 1, 1, 0]], ['milk', [0, 0, 1, 0]], ['You', [0, 0, 0, 1]], ['likes', [0, 0, 0, 1]], ['me', [0, 0, 0, 1]]]