erased swap files from repo, apparently
[BS_AY250.git] / week5 / d.py
blob8c16953c1c8cfdfa8eca5bc1da3d82f38ec10a3d
1 '''
2 AY250 HW5 D
3 Show web page of polling data from one state
4 Author: Bryan Steinbach
5 '''
7 import sys
8 import os
9 import sqlite3
10 import webbrowser
12 import numpy as np
14 tablefn = 'poll'
16 conn = sqlite3.connect(tablefn)
19 # sanity check
20 #c.execute('select * from polls where state = "CA"')
22 def getpic(name):
23 ''' Fetch image URL from candidate's name '''
24 if name == '': return ''
25 c = conn.cursor()
26 c.execute(''' select url from pics where name = '%s' '''%name)
27 (url,) = c.next()
28 c.close()
30 return url
32 def retrieve_state(state):
33 ''' Fetch information about state and render to web page '''
34 c = conn.cursor()
35 c.execute('''select polls.state,polls.gop,polls.dem,polls.ind,polls.date1,polls.pollster,names.gop,names.dem,names.ind,names.incpar
36 from polls,names,pics where polls.state = '%s' and names.state = '%s' order by polls.date1 desc limit 1'''%(state,state))
38 state,gopfrac,demfrac,indfrac,date,pollster,gopname,demname,indname,incparname = c.next()
40 c.close()
42 goppic = getpic(gopname)
43 dempic = getpic(demname)
44 indpic = getpic(indname)
46 fracs = np.array([gopfrac,demfrac,indfrac])
47 partys = ['Republican','Democrat','Independent']
49 favi = np.argmax(fracs)
50 favp = partys[favi]
52 fn = state+'.html'
53 with open(fn,'w') as f:
54 print>>f,"<html>"
55 print>>f,"<body>"
56 print>>f,"<h1>State of "+state+" polling</h1>"
58 if gopname:
59 print>>f,"<h2>Republican candidate: ",gopname,"</h2>"
60 print>>f,"<img src='"+goppic+"'></img>"
61 print>>f,"<p>"
62 print>>f,"Polling: ",gopfrac
64 print>>f,"<p><p>"
66 if demname:
67 print>>f,"<h2>Democratic candidate: ",demname,"</h2>"
68 print>>f,"<img src='"+dempic+"'></img>"
69 print>>f,"<p>"
70 print>>f,"Polling: ",demfrac
72 print>>f,"<p><p>"
74 if indname:
75 print>>f,"<h2>Independent candidate: ",indname,"</h2>"
76 print>>f,"<img src='"+indpic+"'></img>"
77 print>>f,"<p>"
78 print>>f,"Polling: ",indfrac
80 print>>f,"<p><p>"
82 print>>f,"The incumbent party is "+incparname+"."
83 if favp != incparname:
84 print>>f,"We expect that to change to %s this election."%favp
85 else:
86 print>>f,"We don't expect that to change this election."
88 print>>f,"</body>"
89 print>>f,"</html>"
91 webbrowser.open(fn)
94 try:
95 state = sys.argv[1]
96 except IndexError:
97 print "usage: python d.py <2 char state abbreviation>"
98 exit(1)
99 retrieve_state(state)