我有一堆格式如下的文件:
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
同样,它不是从最小的数字开始,这是错误的输出。我怀疑它与读取文件时的循环有关,或者我不确定的东西,因为我已经在这一点上停留了一段时间。
我真的可以在这里使用一些输入。
当我使用
。最常见的()
代替
。项目()
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
甚至还没有接近排序