"Untitled Post" - Views: 120 · Hits: 120 - Type: Unlisted

from pprint import pprint

curfile = open('ok_results.csv')
header_line = curfile.readline()
candidates = set(['"MITT ROMNEY"', '"RON PAUL"', '"RICK PERRY"', '"MICHELE BACHMANN"', '"RICK SANTORUM"', '"JON HUNTSMAN"', '"NEWT GINGRICH"'])
results = {} # dict from precinct to precinct results

for i,line in enumerate(curfile):
   if 'DEMOCRAT' in line:    continue

   fields    = line.split(',')
   precinct  = fields[9]
   candidate = fields[7]
   try:
      votes = int(fields[10])
   except ValueError: # some lines are problematic because they have commas inside a field, but none should be votes for repub candidates.
      # sample problem line: "03/06/2012","GARVIN","CITY OF LINDSAY",42501,"FOR COUNCILMAN NO. 1, NO. 2, NO. 3","",1,"ERIC KEELER","","250001",56,0,0,56
      votes = 0

   if candidate not in candidates: continue # avoid various trivial third parties, proposition votes, etc
   results.setdefault(precinct,{})[candidate] = votes

#pprint(results)


# Now we can summarize/analyze
for precinct in results:
   precinct_results = results[precinct]
   totalvotes = sum(precinct_results.values())
   if totalvotes == 0: continue
   romneyvotes = precinct_results['"MITT ROMNEY"']
   print totalvotes, romneyvotes, float(romneyvotes)/totalvotes