如何计算文件python的每一行中的数字?

时间:2017-10-13 14:09:57

标签: python-3.x

在我的文件中,我的每个行号都在0到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

我想计算在这个文件中重复的每个数字的数量:

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)) 

3 个答案:

答案 0 :(得分:2)

这肯定不是在错误处理方面做到这一点的最佳方式,但它符合您的基本要求。

# 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)."

鉴于您的文件,它会产生:

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.

答案 1 :(得分:0)

创建一个计数器字典,并在阅读时将这些行附加到它。完成后,您可以使用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

输入的numbers.txt文件包含:

1
2
3
2
3
3
1
1
1

答案 2 :(得分:0)

如果您使用collections模块,检查您的号码计数非常简单。在其中,有一个名为Counter的类可以计算可以抛出的任何可清除对象。在这种情况下,您可以毫无问题地为其提供字符串或数字。您需要使用最新版本的Python才能使用此处演示的f字符串:

#! /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()