获取唯一计数排序

2024-04-28 19:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的文件:

15
17
18
21
14
18
14
13
17
11
11
18
15
15
12
17
9
10
12
17
14
17
etc

以下脚本读取这些文件:

import os
from collections import Counter


def main():
    p = './newR'
    fd = os.listdir(p)
    countUniq(p, fd)


def writeFile(fd, fhp, fcount):
    fo = './nnewR/'+fd+'.txt'
    with open(fo, 'a') as f:    
        r = '%s %s\n' % (fhp, fcount)
        f.write(r)


def countUniq(path, dirs):
    for pfiles in dirs:
        pathN = os.path.join(path, pfiles)
        with open(pathN, 'r') as infile:
            data = infile.read()
        fileN = os.path.basename(pathN)
        stripFN = os.path.splitext(fileN)[0]
        fDate = stripFN.split('_')[0]
        countr = Counter()
        countr.update([int(d) for d in data.split()])
        for line, count in countr.items():
            writeFile(fDate, line, count)
main()

这将输出以下文件:

20130813.txt
20130819.txt
20130825.txt
20130831.txt
etc

让我们看一下第一个要测试的文件,看看它是否完成了任务:

51 4
9 4
10 36
11 48
12 132
13 144
14 148
15 133
16 52
17 105
18 61
19 20
20 12
21 16
22 20
23 8

这很奇怪,为什么它不是以9这样的最小数字开头,而是以51开头呢!!你知道吗

如果我随机检查另一个文件:

28 4
9 20
10 122
11 136
12 298
13 302
14 397
15 314
16 218
17 264
18 148
19 93
20 32
21 49
22 16
23 13
24 8
25 4
60 4

同样,它不是以最小的数字开始的,这是错误的输出。我怀疑这与读取文件时的循环有关,或者与我不确定的内容有关,因为我已经在这一点上停留了一段时间。你知道吗

我真的需要一些意见。你知道吗

当我使用

.most_common()

而不是

.items()

for line, count in countr.most_common():
print fDate, line, count

我把所有的东西都搞混了,甚至没有像.items()那样分类:

20130822 14 379
20130822 15 336
20130822 12 306
20130822 13 292
20130822 17 266
20130822 16 200
20130822 18 172
20130822 11 132
20130831 14 364
20130831 15 353
20130831 12 302
20130831 13 300
20130831 17 281
20130831 16 244
20130831 18 153
20130831 11 133
20130831 10 121
20130831 19 73
20130831 21 32
20130820 14 387
20130820 15 338
20130820 12 308
20130820 13 300
20130820 17 282
20130820 16 193
20130820 18 169
20130820 11 136
20130820 10 116
20130820 19 85
20130820 21 44

甚至不可能被分类


Tags: 文件pathintxtforosdefcount
2条回答

Counter按任意顺序迭代其元素,但其repr按计数的降序显示元素。你知道吗

如果要对它们进行排序,请使用.most_common()按出现次数排序,或使用sorted()按键排序:

>>> c = collections.Counter({6: 2892, 67: 1921, 3: 1821, 35: 304})
>>> for i, count in c.iteritems(): print i,count
... 
35 304
67 1921
3 1821
6 2892
>>> for i, count in c.most_common(): print i,count
... 
6 2892
67 1921
3 1821
35 304
>>> for i, count in sorted(c.items()): print i,count
... 
3 1821
6 2892
35 304
67 1921

不确定是哪个平台,但如果shell是一个选项:

sort myfile.txt | uniq -c | sort -nr

相关问题 更多 >