在python中重新排列字符串结构

2024-04-24 08:50:33 发布

您现在位置: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

你知道如何实现这个结构吗?或者类似的输出? 谢谢您。你知道吗


Tags: 文件keyintokenforindexpdfvalue
3条回答

好吧,你可以有一个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)

只要对代码进行最少的修改,就可以按如下方式完成

for key, value in countDict.items():
    entries = [key]
    for word, count in value.items():
        for token, index in vocabDict.items():
                if word==token:
                    entries.append(str(index) + " : " + str(count))
                    print(key,index,count)

    print(", ".join(entries))

当然,您想要的结构可能是defaultdict of dicts。我给你看看。你知道吗

{
    'PP3188': {
        2498: 1,
        1834: 10,
        2063: 1
    },
    'PP3278': {
        447: 1,
        1458:1
    },
    'PP3160': {
        2433: 5,
        1889: 2
    }
}

下面是示例代码。你知道吗

from collections import defaultdict

... some code ...

data = defaultdict(dict)

for key, value in countDict.items():
    for word, count in value.items():
        for token, index in vocabDict.items():
                if word==token:
                    data[key][index] = count

我和@Epion答案的区别在于,在他的答案中,dict的key是PPxxxx,value是元组列表,而我的dict是dict的value。你知道吗

相关问题 更多 >