Reputation: 17
I have the following code which opens a text file that contains comma separated numbers.
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)
The results are:
['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})
What I am trying to accomplish is for the program to read the first line, run Counter to check the number of times a number appears, then read the second line, re-Count (i.e. add count to previous count).
Where am I going wrong? It's currently not even counting the numbers, since there are more than 1 instances of "1".
Upvotes: 0
Views: 791
Reputation: 118011
You can use the update
method of collections.Counter
, otherwise you keep overwriting counts
each iteration
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)
Result
Counter({1: 3, 3: 2, 5: 2, 2: 1, 4: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1})
Upvotes: 2
Reputation: 199
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)
Is that right code you want?
Upvotes: 0