获得排序的唯一计数

时间:2013-09-07 16:00:23

标签: 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

哪个甚至没有接近排序

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

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