Из стандартной библиотеки:
С учетом
Пример файла test.txt
:
Voter ID,County,Candidate
12864552,Marsh,Khan
17444633,Marsh,Correy
19330107,Marsh,Khan
19865775,Queen,Khan
11927875,Marsh,Khan
19014606,Marsh,Li
17775191,Queen,Correy
14003692,Marsh,Khan
12864552,Marsh,Khan
17444633,Marsh,Correy
19330107,Marsh,Khan
19865775,Queen,Khan
11927875,Marsh,Khan
19014606,Marsh,Li
17775191,Queen,Correy
14003692,Marsh,Khan
код
import collections as ct
filepath = "test.txt"
with open(filepath) as f:
votes = ct.Counter()
header = next(f)
for line in f:
candidate = line.split(",")[-1].strip()
votes[candidate] += 1
С другой стороны
import csv
import collections as ct
filepath = "test.txt"
with open(filepath) as f:
votes = ct.Counter()
reader = csv.reader(f)
next(reader)
for line in reader:
candidate = line[-1]
votes[candidate] += 1
Демо
votes
# Counter({'Khan': 10, 'Correy': 4, 'Li': 2})
votes.most_common(1)
# [('Khan', 10)]
См. Также документы для collections.Counter
и csv
модулей.