2017-07-28 68 views
0

我有以下代码,它将打开一个包含逗号分隔数字的文本文件。Python - 如何使用计数器逐行计数

from collections import Counter 

with open("lottoresults.txt") as inf: 
    all_lines = [inf.read()] 
    print(all_lines) 
    for each_line in all_lines: 
     print(each_line) 
     counts = Counter(each_line) 
     set = each_line.replace("", "").split() 
     print(set) 
     for numbers in set: 
      nums = [int(i) for i in numbers.replace(",", "\n").split()] 
      print(nums) 
      for number in nums: 
       counts = Counter(nums) 
print(counts) 

的结果是:

['1,2,3,4,5\n1,3,5,6,7\n1,8,9,10,11'] 
1,2,3,4,5 
1,3,5,6,7 
1,8,9,10,11 
['1,2,3,4,5', '1,3,5,6,7', '1,8,9,10,11'] 
[1, 2, 3, 4, 5] 
[1, 3, 5, 6, 7] 
[1, 8, 9, 10, 11] 
Counter({8: 1, 1: 1, 10: 1, 11: 1, 9: 1}) 

我试图做到的是让程序读取的第一线,违背检查出现了许多的次数,然后读取第二行,重新计数(即将计数添加到以前的计数)。

我哪里错了?目前甚至没有计算数字,因为有超过1个“1”的实例。

+1

提示:你是否观察到输出导致最后一个数组的计数?这意味着,计数器正在重新初始化,但没有更新。 –

+0

我确实观察过它,但现在我明白了为什么它将数字计数为一次!谢谢。 –

回答

0
from collections import Counter 

cnt = Counter() 
with open("lottorresults.txt") as f: 
    for line in f.readlines(): 
     numbers = [int(n) for n in line.strip().split(",")] 
     cnt.update(numbers) 

那是正确的代码你想要什么?

+0

就是这样。一旦你看到它正常工作,它就会变得非常有意义。我试图通过在最后封装它来计算每一个,当时我真的应该开始使用它... –

2

您可以使用collections.Counterupdate方法,否则你一直覆盖counts每次迭代

from collections import Counter 

counts = Counter() 
with open("lottoresults.txt") as inf: 
    for each_line in inf: 
     counts.update(int(i) for i in each_line.split(',')) 
print(counts) 

结果

Counter({1: 3, 3: 2, 5: 2, 2: 1, 4: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1}) 
+0

+1 * update()*方法可能是最干净的方法。仅供参考,在c.update(map(int,line.split(',')))中使用* map()*或在c.update中至少使用生成器表达式(int(i)for line in line.split(','))''。 –

+0

良好的发电机表达式呼叫 – CoryKramer