-
Notifications
You must be signed in to change notification settings - Fork 4
/
csv_export.py
81 lines (77 loc) · 2.11 KB
/
csv_export.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
import json
import csv
from api.models import *
from api import db
import sys
import operator
def wards(year, ballot, lvl_id):
rows = db.session.query(Ward).filter(Ward.year == year).all()
results = []
for row in rows:
if (ballot == "national"):
dataset = populate_dataset(json.loads(row.results_national))
else:
dataset = populate_dataset(json.loads(row.results_provincial))
if (dataset):
dataset[lvl_id] = row.as_dict()[lvl_id]
results.append(dataset)
return results
def populate_dataset(data):
vote_count = sorted(data["vote_count"].iteritems(), key=operator.itemgetter(1), reverse = True)
if (data["meta"]["vote_count"] > 0):
result = {
"total_votes": data["meta"]["total_votes"],
"spoilt_votes": data["meta"]["spoilt_votes"],
"vote_count": data["meta"]["vote_count"],
"num_registered": data["meta"]["num_registered"],
"winner": vote_count[0][0],
"winner_votes": vote_count[0][1],
"winner_perc": vote_count[0][1] / data["meta"]["vote_count"],
"runner_up": vote_count[1][0],
"runner_up_votes": vote_count[1][1],
"runner_up_perc": vote_count[1][1] / data["meta"]["vote_count"],
"difference_perc": (vote_count[0][1] - vote_count[1][1]) / data["meta"]["vote_count"]
}
else:
result = False
# print result
return result
def print_csv(data, fname, lvl_id):
# print data
fieldnames = [
lvl_id,
"total_votes",
"spoilt_votes",
"vote_count",
"num_registered",
"winner",
"winner_votes",
"winner_perc",
"runner_up",
"runner_up_votes",
"runner_up_perc",
"difference_perc"
]
with open(fname, 'wb') as csvfile:
csvwriter = csv.DictWriter(csvfile, fieldnames)
csvwriter.writeheader()
csvwriter.writerows(data)
print "All done"
if __name__ == "__main__":
# print len(sys.argv)
if (len(sys.argv) == 0):
print "Usage: python csv_export.py level national/provincial year filename"
sys.exit(1);
if (len(sys.argv) == 4):
year = "2014"
else:
year = sys.argv[3]
lvl = sys.argv[1]
# print lvl
ballot = sys.argv[2]
fname = sys.argv[3]
if (lvl == "wards"):
lvl_id = "ward_id"
data = wards(year, ballot, lvl_id)
print_csv(data, fname, lvl_id)
sys.exit(0)