Skip to content

Commit

Permalink
Merge pull request #43 from btstevens89/master
Browse files Browse the repository at this point in the history
Added functionality to retrieve player/coach/umpire information on per game basis
  • Loading branch information
panzarino committed Jul 18, 2017
2 parents 5983496 + c920af0 commit 6eee3e2
Show file tree
Hide file tree
Showing 4 changed files with 159 additions and 1 deletion.
85 changes: 85 additions & 0 deletions examples/example_players.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env python

import mlbgame
import re

def rename(name):
return re.sub(r'_', ' ', name).title()

game = mlbgame.day(2017, 7, 9, away='Orioles')[0]
players = mlbgame.players(game.game_id)

print(game.home_team + ' vs ' + game.away_team + ' (' + str(game.date) + ')')

types = ['home', 'away']
for type in types:
print(' ' + getattr(game, type + '_team') + ' Information:')
team_players = getattr(players, type + '_players')
team_coaches = getattr(players, type + '_coaches')

print(' Coaching Staff:')
for coach in team_coaches:
print(' {0}: {first} {last}'.format(rename(coach['position']), **coach))

print(' Starting Lineup:')
starting_lineup = list(filter(lambda x: 'bat_order' in x.keys(), team_players))
for player in sorted(starting_lineup, key=lambda k: k['bat_order']):
print(' {bat_order}. {first} {last} ({game_position})'.format(**player))

print(' Umpires:')
for umpire in players.umpires:
print(' {0}: {first} {last}'.format(rename(umpire['position']), **umpire))

"""
Twins vs Orioles (2017-07-09 13:10:00)
Twins Information:
Coaching Staff:
Manager: Paul Molitor
Hitting Coach: James Rowson
Assistant Hitting Coach: Rudy Hernandez
Pitching Coach: Neil Allen
First Base Coach: Jeff Smith
Third Base Coach: Gene Glynn
Bench Coach: Joe Vavra
Bullpen Coach: Eddie Guardado
Major League Coach: Jeff Pickler
Bullpen Catcher: Nate Dammann
Starting Lineup:
0. Kyle Gibson (P)
1. Brian Dozier (2B)
2. Robbie Grossman (DH)
3. Max Kepler (RF)
4. Miguel Sano (3B)
5. Kennys Vargas (1B)
6. Eddie Rosario (LF)
7. Jorge Polanco (SS)
8. Chris Gimenez (C)
9. Zack Granite (CF)
Orioles Information:
Coaching Staff:
Manager: Buck Showalter
Hitting Coach: Scott Coolbaugh
Assistant Hitting Coach: Howie Clark
Pitching Coach: Roger McDowell
First Base Coach: Wayne Kirby
Third Base Coach: Bobby Dickerson
Bench Coach: John Russell
Bullpen Coach: Alan Mills
Coach: Einar Diaz
Starting Lineup:
0. Ubaldo Jimenez (P)
1. Seth Smith (RF)
2. Manny Machado (3B)
3. Jonathan Schoop (2B)
4. Adam Jones (CF)
5. Mark Trumbo (DH)
6. Trey Mancini (1B)
7. Hyun Soo Kim (LF)
8. Caleb Joseph (C)
9. Ruben Tejada (SS)
Umpires:
Home: Lance Barrett
First: Bill Welke
Second: Jim Reynolds
Third: Sean Barber
"""
6 changes: 6 additions & 0 deletions mlbgame/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,12 @@ def teams():
"""Return list of Info objects for each team"""
return [mlbgame.info.Info(x) for x in mlbgame.info.team_info()]


def disabled_list(team_id):
"""Return Injury object that contains DL info for a team"""
return mlbgame.injury.Injury(team_id)


def players(game_id):
"""Return list players/coaches/umpires for game matching the game id."""
return mlbgame.game.Players(mlbgame.game.players(game_id))
14 changes: 13 additions & 1 deletion mlbgame/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ def get_overview(game_id):
raise ValueError("Could not find a game with that id.")


def get_players(game_id):
"""Return the players file of a game with matching id."""
year, month, day = get_date_from_game_id(game_id)
try:
print(GAME_URL.format(year, month, day, game_id, "players.xml"))
return urlopen(GAME_URL.format(year, month, day,
game_id,
"players.xml"))
except HTTPError:
raise ValueError("Could not find a game with that id.")


def get_properties():
"""Return the current mlb properties file"""
try:
Expand All @@ -75,4 +87,4 @@ def get_properties():

def get_date_from_game_id(game_id):
year, month, day, _discard = game_id.split('_', 3)
return year, month, day
return int(year), int(month), int(day)
55 changes: 55 additions & 0 deletions mlbgame/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,3 +321,58 @@ def __init__(self, data):
setattr(self, x, str(data[x]))
element_list.append(x)
self.elements = set(element_list)

def players(game_id):
"""Gets player/coach/umpire information for the game with matching id."""
# get data
data = mlbgame.data.get_players(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()

output = {}
output['game_id'] = game_id

# get player/coach data
for team in root.findall('team'):
type = team.attrib['type'] + "_team"
# the type is either home_team or away_team
output[type] = {}
output[type]['players'] = []
output[type]['coaches'] = []

for p in team.findall('player'):
player = {}
for key in p.keys():
player[key] = p.get(key)
output[type]['players'].append(player)

for c in team.findall('coach'):
coach = {}
for key in c.keys():
coach[key] = c.get(key)
output[type]['coaches'].append(coach)

# get umpire data
output['umpires'] = []
for u in root.find('umpires').findall('umpire'):
umpire = {}
for key in u.keys():
umpire[key] = u.get(key)
output['umpires'].append(umpire)

return output

class Players(object):
"""Object to hold player/coach/umpire information for a game."""

def __init__(self, data):
"""Creates an overview object that matches the corresponding info in `data`.
`data` should be an dictionary of values.
"""
self.game_id = data['game_id']
self.home_players = data['home_team']['players']
self.home_coaches = data['home_team']['coaches']
self.away_players = data['away_team']['players']
self.away_coaches = data['away_team']['coaches']
self.umpires = data['umpires']

0 comments on commit 6eee3e2

Please sign in to comment.