python - 在python中重新排列字符串结构
问题描述
我正在清理多个 pdf 文件。我结合了两个字典来获得三个输出。文件名是关键,单词索引和单词计数。
for key, value in countDict.items():
for word, count in value.items():
for token, index in vocabDict.items():
if word==token:
print(key,index,count)
三个输出打印为字符串
PP3188 2498 1
PP3188 1834 10
PP3188 2063 1
PP3278 447 1
PP3278 1458 1
PP3160 2433 5
PP3160 1889 2
有没有办法将此输出分组以使其看起来像这样:
PP3188, 2498 : 1, 1834 : 10, 2063 :1
PP3278, 447 : 1, 1458 : 1
PP3160, 2433 : 5, 1889 : 2
知道如何实现这种结构吗?或类似的输出?谢谢你。
解决方案
好吧,你可以有一个defaultdict(list)
结构,它key
作为它的键,值是一个元组列表(index, count)
。
from collections import defaultdict
our_dict = defaultdict(list)
然后,您将执行附加而不是打印:
for key, value in countDict.items():
for word, count in value.items():
for token, index in vocabDict.items():
if word==token:
our_dict[key].append((index, count))
使用这样的结构,您可以在之后打印所有内容:
for key, values_list in our_dict.items():
for (index, count) in values_list:
print(key, index, count)