温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Convert values from a dictionary to a matrix
dictionary list matrix nested-lists python

python - 将值从字典转换为矩阵

发布于 2020-04-04 00:08:26

我已经计算了单词在文本文档中出现的次数,并将这些值放入字典中的次数。现在,我想将这些金额添加到一个矩阵,该矩阵由文本文件作为列,不同的词作为行。这是字典的输出:

{'test1.txt': {'peer': 1, 'appel': 1, 'moes': 1}, 
'test2.txt': {'peer': 1, 'appel': 1}, 
'test3.txt': {'peer': 1, 'moes': 2}, 
'test4.txt': {'peer': 1, 'moes': 1, 'ananas': 1}}

矩阵的输出必须如下所示:

[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
['moes', 1, 0, 2, 1],
['appel', 1, 1, 0, 0],
['peer', 1, 1, 1, 1],
['ananas', 0, 0, 0, 1]]

这是我现在要打印矩阵的代码,但是尚未实现单词在每个文档中出现的次数。

term_freq_matrix = []

list_of_files.insert(0," ")
term_freq_matrix.insert(1, list_of_files)

for unique_word in unique_words:
    unique_word = unique_word.split()
    term_freq_matrix.append(unique_word)

print(term_freq_matrix)

谢谢!

查看更多

提问者
Pythonsnake
被浏览
117
CDJB 2020-01-31 20:27

要在没有外部库的情况下执行此操作:

码:

d = {'test1.txt': {'peer': 1, 'appel': 1, 'moes': 1}, 
    'test2.txt': {'peer': 1, 'appel': 1}, 
    'test3.txt': {'peer': 1, 'moes': 2}, 
    'test4.txt': {'peer': 1, 'moes': 1, 'ananas': 1}}

res = [[''] + list(d.keys())]
for c in set(k for v in d.values() for k in v.keys()):
    res.append([c] + [d[k].get(c, 0) for k in res[0][1:]])

输出:

>>> res
[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
 ['peer', 1, 1, 1, 1],
 ['ananas', 0, 0, 0, 1],
 ['appel', 1, 1, 0, 0],
 ['moes', 1, 0, 2, 1]]