如何计算 .txt 中的多个输入而不仅仅是一个

How to tally multiple inputs in a .txt and not just one

我找到了一个代码,可以计算 .txt 文件中的值列表。但是,出于某种原因,它只会计算出现的第一个值。所以如果文件有这样的东西:

1
2
2
3
2
4

那么只会打印:

Final Tally
1:1

The program will automatically shut down in 5 minutes.

完整代码:

    vote = input('Enter your vote: ')
    file = open('votedata.txt', 'a')
    file.write(vote + '\n')
    print('The system is adding your vote. The next person can vote in 3 seconds.')
    time.sleep(3)
    if vote == 'tally':
        break
#end of loop, beginning of tally
from collections import defaultdict
frequencies = defaultdict(int)
for number in open('votedata.txt'):
    frequencies[int(number)] += 1

for number in sorted(frequencies.keys()):
    print(' ')
    print('Final Tally:')
    print(number, ':', frequencies[number])
    print(' ')
    print('The program will automatically shut down in 5 minutes.')
    time.sleep(300)

我该如何编写才能收集并计算每个整数?

Pandas 可以为您做到这一点

df = pd.read_csv('votedata.txt', names=['votes'])
df['votes'].value_counts().to_dict()

{2: 3, 4: 1, 3: 1, 1: 1}

在您的代码中:

import pandas as pd

    vote = input('Enter your vote: ')
    file = open('votedata.txt', 'a')
    file.write(vote + '\n')
    print('The system is adding your vote. The next person can vote in 3 seconds.')
    time.sleep(3)
    if vote == 'tally':
        break

df = pd.read_csv('votedata.txt', names=['votes'])
frequencies = df['votes'].value_counts().to_dict()

for number in sorted(frequencies.keys()):
    print(' ')
    print('Final Tally:')
    print(number, ':', frequencies[number])
    print(' ')
    print('The program will automatically shut down in 5 minutes.')
    time.sleep(300)

您正在遍历所有输出,因此 5 分钟后您将获得第二个结果:)

您只需删除最后三行的缩进。

虽然 pandas 有效,但我认为对于像这样简单的事情来说有点过分了。

with open("votedata.txt") as fp:
    results = {}
    for row in fp:
        try:
          v = int(float(row))
          if v not in results:
            results[v] = 0
          results[v] += 1
        except:
          print("Invalid Numeric entry")

print( results )

这很简单,不会加载额外的库,不会处理结果,如果用户输入一些垃圾数据,它会在不主动中断程序工作流程的情况下打印错误。