Skip to content

Instantly share code, notes, and snippets.

@seanupton
Last active January 29, 2019 07:05
Show Gist options
  • Save seanupton/7d650ff91f4b94f74d3dbffbe677c535 to your computer and use it in GitHub Desktop.
Save seanupton/7d650ff91f4b94f74d3dbffbe677c535 to your computer and use it in GitHub Desktop.
prop3_sd9_comp.py
#!/usr/bin/env python
from lxml import etree
def slco_election_data():
data = ''
with open('../data/slco_detail_2018.xml') as infile:
data = infile.read()
return etree.fromstring(data)
def sd9_precincts(doc):
contest = doc.find('.//Contest[@key="105"]')
tally = contest.find('VoteType[@name="Number of Precincts for Race"]')
return [p.get('name') for p in tally.findall('Precinct')]
def prop3_result(doc, precinct):
contest = doc.find('.//Contest[@key="895"]')
# Votes for:
choice_for = contest.find('Choice[@text="FOR"]')
_votes_for = choice_for.findall('.//Precinct[@name="%s"]' % precinct)
votes_for = sum([int(p.get('votes', 0)) for p in _votes_for])
# Votes against:
choice_against = contest.find('Choice[@text="AGAINST"]')
_votes_against = choice_against.findall('.//Precinct[@name="%s"]' % precinct)
votes_against = sum([int(p.get('votes', 0)) for p in _votes_against])
return [votes_for, votes_against]
def main():
total_for = 0
total_against = 0
doc = slco_election_data()
precincts = sd9_precincts(doc)
precincts_for = 0
precincts_against = 0
precincts_tie = 0
result = lambda name: prop3_result(doc, name)
for sd9_precinct in precincts:
votes_for, votes_against = result(sd9_precinct)
total_for += votes_for
total_against += votes_against
# considered is not all votes, e.g. abstaining is not considered
considered_votes = votes_for + votes_against
print 'Precinct (%s):' % (sd9_precinct,)
if considered_votes == 0:
print '\tNo votes on measure in this precinct.'
continue
pct_for = 100 * votes_for / float(considered_votes)
pct_against = 100 * votes_against / float(considered_votes)
print '\t%s for (%0.1f%%)' % (votes_for, pct_for)
print '\t%s against (%0.1f%%)' % (votes_against, pct_against)
if votes_for > votes_against:
precincts_for += 1
if votes_for == votes_against:
precincts_tie += 1
if votes_for < votes_against:
precincts_against += 1
considered_votes = total_for + total_against
if considered_votes == 0:
return
pct_for = 100 * total_for / float(considered_votes)
pct_against = 100 * total_against / float(considered_votes)
print 'Total SD9'
print '\t%s FOR (%0.1f%%)' % (total_for, pct_for)
print '\t%s AGAINST (%0.1f%%)' % (total_against, pct_against)
print '\t%s precincts for' % precincts_for
print '\t%s precincts against' % precincts_against
print '\t%s precincts tie' % precincts_tie
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment