user6652926
user6652926

Reputation: 49

How to compute numbers in each line of a file python?

In my file, I have in each line numbers that are between 0 and 256:

20
123
125
109
175
108
210
74
127
86
172
128
187
131
183
230
132
77
30
177
64
60
211
112
79
45

I would like to compute how many each number is repeated in this file:

with open('file', 'w') as f_sb_out:
    for i in range(256):
        total = sum(str(i))
        print('Numre of repetition of '+str(i)+'is', str(total)) 

Upvotes: 0

Views: 83

Answers (3)

Noctis Skytower
Noctis Skytower

Reputation: 22041

Checking the counts of your numbers is super easy if you use the collections module. In it, there is a class named Counter that can count any hashable object you can throw at it. In this case, you can give it strings or numbers without a problem. You will need the latest version of Python to use the f strings demonstrated here:

#! /usr/bin/env python3
import collections


def main():
    with open('numbers.txt', 'rt') as file:
        counts = collections.Counter(map(int, file))
    for key, value in sorted(counts.items()):
        print(f'{key!r} repeats {value!s} times.')


if __name__ == '__main__':
    main()

Upvotes: 0

AlanK
AlanK

Reputation: 9853

Create a counter dictionary and append the lines to it as you read over them. Once you finished you can access the key/values using counter.items()

from collections import Counter

cntr = Counter()

with open('numbers.txt', 'r') as file_in:
    for line in file_in:
        cntr[line.rstrip()] += 1

for k, v in cntr.items():
    print('Numre of repetitions of %s: is %s' % (k, v))

> Numre of repetitions of 1: is 4
> Numre of repetitions of 3: is 3
> Numre of repetitions of 2: is 2

The input numbers.txt file contains:

1
2
3
2
3
3
1
1
1

Upvotes: 0

kchason
kchason

Reputation: 2885

This is certainly not the best way of doing it in terms of error handling, but it meets your basic requirements.

# Declare dict for counts
numCount = dict()

with open('file.txt', 'r') as f_sb_out: # Need to change the form to read, not write
    line = f_sb_out.readline()          # Read the first line
    while line:                         # Loop through each line
        line = f_sb_out.readline()
        line = line.strip()             # Strip any whitespace on either end
        if line == '':                  # Skip any whitespace lines
            continue
        if line in numCount:
            numCount[line] = numCount[line] + 1  # Increment the counter
        else:
            numCount[line] = 1          # Start a new counter

# Print the counts
for num in numCount:
    print "The number " + num + " appeared "+ str(numCount[num]) + " time(s)."

Given your file, it produces:

The number 210 appeared 1 times.
The number 211 appeared 1 times.
The number 60 appeared 1 times.
The number 132 appeared 1 times.
The number 131 appeared 1 times.
The number 64 appeared 1 times.
The number 112 appeared 1 times.
The number 177 appeared 1 times.
The number 175 appeared 1 times.
The number 230 appeared 1 times.
The number 172 appeared 1 times.
The number 79 appeared 1 times.
The number 86 appeared 1 times.
The number 45 appeared 1 times.
The number 183 appeared 1 times.
The number 187 appeared 1 times.
The number 77 appeared 1 times.
The number 108 appeared 1 times.
The number 109 appeared 1 times.
The number 125 appeared 1 times.
The number 127 appeared 1 times.
The number 128 appeared 1 times.
The number 74 appeared 1 times.
The number 30 appeared 1 times.
The number 123 appeared 1 times.

Upvotes: 2

Related Questions