-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.py
232 lines (193 loc) · 7.57 KB
/
parse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import csv
import copy
import functools
import os
import re
class PrecinctResult:
office:str
candidatesToVotes:dict
class OneElection:
ballotName:str
electionName:str
office:str
district:str
party:str # only relevant if isPrimary
year:int
isSingleWinner:bool
isSpecial:bool
isPrimary:bool
def __init__(self, ballotName, oneRow):
self.ballotName = ballotName
self.electionName = oneRow.electionName
self.office = oneRow.office
self.district = oneRow.district
self.year = int(self.ballotName[0:4])
self.isSingleWinner = self.is_single_winner(self.office)
self.isPrimary = 'Primary' in ballotName
self.isSpecial = 'Special' in ballotName
self.isRetention = 'Retention' in self.office
self.party = oneRow.party if self.isPrimary else None
@classmethod
def is_single_winner(self, office):
known_single_winner_substrings = (
"Representative in",
"President of the United States",
"Attorney General",
"State Treasurer",
"Representative in",
"Senator in",
"United States Senator",
"Auditor General",
"Governor",
"Lieutenant Governor")
return any(substring in office for substring in known_single_winner_substrings)
def getOtherPartyPrimary(self):
assert self.isPrimary
e = copy.copy(self)
if self.party == 'Democratic':
e.party = 'Republican'
elif self.party == 'Republican':
e.party = 'Democratic'
else:
raise ValueError("Unexpected party name " + str(self.__dict__))
return e
def _fields(self):
if self.isPrimary:
return (self.ballotName, self.electionName, self.office, self.district, self.party)
return (self.ballotName, self.electionName, self.office, self.district)
def __hash__(self):
return hash(self._fields())
def __eq__(self, other):
return self._fields() == other._fields()
class OneRow:
electionName:str
county:str
office:str
party:str
district:str
candidateName:str
numVotes:int
def __init__(self, rawRowData):
self.electionName = rawRowData['Election Name']
self.county = rawRowData['County Name']
self.office = rawRowData['Office Name']
self.district = rawRowData['District Name']
self.candidateName = rawRowData['Candidate Name']
self.party = rawRowData['Party Name']
self.numVotes = self._to_int(rawRowData['Votes'])
# For judge re-elections
self.yesVotes = self._to_int(rawRowData['Yes Votes'])
self.noVotes = self._to_int(rawRowData['No Votes'])
def isBallotInitiative(self):
ballotInitiativeNamesContain = (
'PROPOSED CONSTITUTIONAL',
'Joint Resolution',
'Bond Question',
'Infrastructure Referendum',
)
return any(c in self.office for c in ballotInitiativeNamesContain)
def _to_int(self, votes):
if votes == '':
votes = '0'
return int(votes.replace(',', ''))
def __repr__(self):
return "%s (%s) for %s in %s: %s received %d votes" % (self.electionName, self.county, self.office, self.district, self.candidateName, self.numVotes)
def parseFile(filepath):
d = []
with open(filepath, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
d.append(OneRow(row))
return d
def parseAllFiles(maindir):
dataPerBallotName = {}
for filename in os.listdir(maindir):
if not filename.endswith('.CSV'):
continue
filepath = os.path.join(maindir, filename)
print("Parsing ", filepath)
result = parseFile(filepath)
dataPerBallotName[filename] = result
return dataPerBallotName
def createElectionIfDNE(resultsPerElection, election):
if election in resultsPerElection:
return
resultsPerElection[election] = {}
if election.isPrimary:
otherPartyPrimary = election.getOtherPartyPrimary()
if otherPartyPrimary not in resultsPerElection:
resultsPerElection[otherPartyPrimary] = {}
def getPrecinctResultsPerElection(dataPerBallotName):
resultsPerElection = {}
for ballotName, election in dataPerBallotName.items():
for row in election:
if row.isBallotInitiative():
continue
election = OneElection(ballotName, row)
createElectionIfDNE(resultsPerElection, election)
results = resultsPerElection[election]
# Initialize num votes if needed
if row.candidateName not in results:
if election.isRetention:
results[row.candidateName + " (yes)"] = 0
results[row.candidateName + " (no)"] = 0
else:
results[row.candidateName] = 0
# Accumulate votes
if election.isRetention:
results[row.candidateName + " (yes)"] += row.yesVotes
results[row.candidateName + " (no)"] += row.noVotes
else:
results[row.candidateName] += row.numVotes
return resultsPerElection
def summaryString(name, votePct):
if not isinstance(votePct, str):
return "%s (%02.1f%%)" % (name, 100*votePct)
else:
return "%s (no votes!)" % (name)
def sortkey(a, b):
try:
return a<b
except:
return str(a) < str(b)
def main():
maindir = 'downloads'
dataPerBallotName = parseAllFiles(maindir)
resultsPerElection = getPrecinctResultsPerElection(dataPerBallotName)
with open('results.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerow(['year',
'ballotname',
'electionname',
'district',
'office',
'party (if primary)',
'special election?',
'primary?',
'retention?',
'single-winner?',
'num candidates',
'percent winner won with',
*['candidate %d'%d for d in range(1,11)]])
for election, votes in resultsPerElection.items():
totalVotes = sum(votes.values())
maxVotes = max(votes.values()) if votes else 0 # handle empty primaries
eachVotePct = [v/totalVotes if totalVotes != 0 else "N/A" for v in votes.values()]
namesAndVotes = list(zip(eachVotePct, votes.keys()))
namesAndVotes.sort(reverse=True, key=functools.cmp_to_key(sortkey))
namesAndVotes = [summaryString(nv[1], 100*nv[0]) for nv in namesAndVotes]
csvwriter.writerow([election.year,
election.ballotName,
election.electionName,
election.district,
election.office,
election.party,
election.isSpecial,
election.isPrimary,
election.isRetention,
election.isSingleWinner,
len(votes),
maxVotes/totalVotes if totalVotes != 0 else "N/A",
*namesAndVotes])
if __name__ == "__main__":
main()