我找到了一个代码,可以计算 .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)
我如何编写它以便它收集和统计每个整数?