Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ def eval(cmd, input=None):
return wordOfTheDay.eval()
elif cmd['service'] == 'MBTA':
return MBTA.eval(cmd['args'])
elif cmd['service'] == 'E':
return elections.eval(input)
else:
return "ERROR 42: service not recognized"

Expand All @@ -40,6 +42,8 @@ def special(incoming):
body = weather.special
elif incoming.upper() == "MBTA":
body = MBTA.special
elif incoming.upper() == 'ELECTIONS':
body = elections.special
elif incoming.upper() == "DEMO":
## welcome/instructions
body = 'Thanks for using Harvard Now!\n'
Expand All @@ -52,6 +56,7 @@ def special(incoming):
body += 'Sending part of a name gives all information associated with that name.\n'
body += 'For example sending Quad will give information about the shuttle stop Quad and the shuttle'
body += 'route Quad Yard Express and sending Quincy laundry will give all the laundry rooms in Quincy.\n'
body += '2018 National Election results are available by sending the name of state, race, and district (if applicable).\n'
return body

## main function
Expand Down
1 change: 1 addition & 0 deletions data.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@
{'service': 'S', 'args':{'endpoint': 'route', 'routeid': '4007610' , 'label': 'Quad Stadium Express Shuttle Route'}, 'tags':['QUAD', 'STADIUM', 'EXPRESS', 'SHUTTLE', 'ROUTE']},
{'service': 'S', 'args':{'endpoint': 'route', 'routeid': '4007650' , 'label': 'Allston Campus Express Shuttle Route'}, 'tags':['ALLSTON', 'CAMPUS', 'EXPRESS', 'SHUTTLE', 'ROUTE']},
{'service': 'W', 'args':{}, 'tags':['WEATHER']},
{'service': 'E', 'args':{}, 'tags':['ELECTIONS']},
{'service': 'D', 'args':{}, 'tags':['WORDOFTHEDAY']},
{'service': 'MBTA', 'args': {'pg': ['green/lake']}, 'tags': ['MBTA', 'SUBWAY', 'T', 'SCHEDULE', 'LINE', 'GREEN', 'COLLEGE', 'BOSTON']},
{'service': 'MBTA', 'args': {'pg': ['green/sougr']}, 'tags': ['MBTA', 'SUBWAY', 'T', 'SCHEDULE', 'LINE', 'ST', 'STREET', 'SOUTH', 'GREEN']},
Expand Down
1 change: 1 addition & 0 deletions services/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
from weather import weather
from wordOfTheDay import wordOfTheDay
from MBTA import MBTA
from elections import elections
8 changes: 8 additions & 0 deletions services/elections/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Election Results

“This service provides data from politico.com on the midterm election results. Users provide a state, race, and district.”

Election results are requested with the following syntax: “Elections [STATE] [RACE] [DISTRICT (optional)]"
where race is “House”, ”Senate”, or “Governor.” DISTRICT is only required for house.

Created by Andrea Zhang, Daniel Gottesman, and Jordan Barkin.
Empty file added services/elections/__init__.py
Empty file.
112 changes: 112 additions & 0 deletions services/elections/elections.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# 2018 election results service
# Created by Andrea Zhang, Daniel Gottesman, and Jordan Barkin.

import urllib2, urllib
import re
from random import randint
from bs4 import BeautifulSoup

#########################################
## Election Data Gathering Function ##
#########################################
def getElectionData(state, race, district):
state = state.lower()

if not isState(state):
return randomCapitalize(state + " is not a state.")

if race == 'house':
race = 'district-' + str(district).zfill(2)

state = state.replace(" ", "-")
url = 'https://www.politico.com/election-results/2018/' + state + '/'
hdr = {'User-Agent': 'Chrome'}
req = urllib2.Request(url,headers=hdr)
website = urllib2.urlopen(req)
soup = BeautifulSoup(website.read(), 'html.parser')

try:
section = soup.find("section", {"name" : race})
results_table = section.find_all("td", {"class" : "candidate"})

for i in range(len(results_table)):
results_table[i] = results_table[i].get_text()
results_table[i] = results_table[i].strip()

try:
results_table.remove("Other")
except:
pass

results_table = [x.replace("*", " (Incumbent)") for x in results_table]
winner = results_table[0]
losers = results_table[1:]
loserstring = ", ".join(losers)

body = "Winner: " + winner + "\n" + "Loser(s): " + loserstring

except Exception, e:
print str(e)
return "Could not find data."

return body

############################
## Top-Level ##
############################

def makeSpecial():
s = 'This will get election results for the 2018 midterms given a state and a race (governor, senate, or house + district).'
return s

## return proper format
special = makeSpecial()

def isState(state):
states = ['alabama', 'alaska', 'arizona', 'arkansas', 'california', 'colorado', 'connecticut', 'delaware',
'florida', 'georgia', 'hawaii', 'idaho', 'illinois', 'indiana', 'iowa', 'kansas', 'kentucky', 'louisiana',
'maine', 'maryland', 'massachusetts', 'michigan', 'minnesota', 'mississippi', 'missouri', 'montana',
'nebraska', 'nevada', 'new hampshire', 'new jersey', 'new mexico', 'new york', 'north carolina',
'north dakota', 'ohio', 'oklahoma', 'oregon', 'pennsylvania', 'rhode island', 'south carolina',
'south dakota', 'tennessee', 'texas', 'utah', 'vermont', 'virginia', 'washington',
'west virginia', 'wisconsin', 'wyoming']
return state in states

def eval(input):
length = len(input)

state = None
race = None
district = None

if(length >= 1):
state = input[0].lower()
if(length >= 2):
race = input[1].lower()
if(length >= 3):
district = str(input[2])

if not state:
return "Please specify a state."

if district:
return getElectionData(state, race, district) if (race == "house") else "Please specify a district if looking for house"
elif race:
return getElectionData(state, race, None)
else:
return "Please specify a race."


def randomCapitalize(string):
# s = ""
# for i in string:
# num = randint(0,1)
# if num == 1:
# s += i.upper()
# else:
# s += i
# return s
return "".join([i.upper() if randint(0,1) else i.lower() for i in string])

if __name__ == "__main__":
print(eval(["florida", "governor"]))
13 changes: 13 additions & 0 deletions tests/lower.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
states = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado",
"Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois",
"Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland",
"Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana",
"Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York",
"North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania",
"Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah",
"Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]

for i in range(len(states)):
states[i] = states[i].lower()

print(states)
109 changes: 109 additions & 0 deletions tests/webpractice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import urllib2, urllib
import re
from random import randint
from bs4 import BeautifulSoup

#########################################
## Election Data Gathering Function ##
#########################################
def getElectionData(state, race, district):
state = state.lower()
if not isState(state):
return randomCapitalize(state + " is not a state.")

if race == 'house':
race = 'district-' + str(district).zfill(2)

state = state.replace(" ", "-")
url = 'https://www.politico.com/election-results/2018/' + state + '/'
hdr = {'User-Agent': 'Chrome'}
req = urllib2.Request(url,headers=hdr)
website = urllib2.urlopen(req)
soup = BeautifulSoup(website.read(), 'html.parser')

try:
section = soup.find("section", {"name" : race})
results_table = section.find_all("td", {"class" : "candidate"})
for i in range(len(results_table)):
results_table[i] = results_table[i].get_text()
results_table[i] = results_table[i].strip()

try:
results_table.remove("Other")
except:
pass

results_table = [x.replace("*", " (Incumbent)") for x in results_table]
winner = results_table[0]
losers = results_table[1:]
loserstring = ", ".join(losers)
body = "Winner: " + winner + "\n" + "Loser(s): " + loserstring


except Exception, e:
print str(e)
return "Could not find data."

return body

############################
## Top-Level ##
############################

def makeSpecial():
s = 'This will get the word of the day.'
return s

## return proper format
special = makeSpecial()

def isState(state):
states = ['alabama', 'alaska', 'arizona', 'arkansas', 'california', 'colorado', 'connecticut', 'delaware',
'florida', 'georgia', 'hawaii', 'idaho', 'illinois', 'indiana', 'iowa', 'kansas', 'kentucky', 'louisiana',
'maine', 'maryland', 'massachusetts', 'michigan', 'minnesota', 'mississippi', 'missouri', 'montana',
'nebraska', 'nevada', 'new hampshire', 'new jersey', 'new mexico', 'new york', 'north carolina',
'north dakota', 'ohio', 'oklahoma', 'oregon', 'pennsylvania', 'rhode island', 'south carolina',
'south dakota', 'tennessee', 'texas', 'utah', 'vermont', 'virginia', 'washington',
'west virginia', 'wisconsin', 'wyoming']
return state in states

def eval(input):
length = len(input)

state = None
race = None
district = None

if(length >= 1):
state = input[0]
if(length >= 2):
race = input[1]
if(length >= 3):
district = str(input[2])

print(state + ", " + race + ", " + str(district))

if not state:
return "Please specify a state."

if district:
return getElectionData(state, race, district) if (race == "house") else "Please specify a district if looking for house"
elif race:
return getElectionData(state, race, None)
else:
return "Please specify a race."



def randomCapitalize(string):
s = ""
for i in string:
num = randint(0,1)
if num == 1:
s += i.upper()
else:
s += i
return s


print(eval(["mexico", "house", 2]))