Skip to content

Commit 6eee3e2

Browse files
authored
Merge pull request #43 from btstevens89/master
Added functionality to retrieve player/coach/umpire information on per game basis
2 parents 5983496 + c920af0 commit 6eee3e2

File tree

4 files changed

+159
-1
lines changed

4 files changed

+159
-1
lines changed

examples/example_players.py

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python
2+
3+
import mlbgame
4+
import re
5+
6+
def rename(name):
7+
return re.sub(r'_', ' ', name).title()
8+
9+
game = mlbgame.day(2017, 7, 9, away='Orioles')[0]
10+
players = mlbgame.players(game.game_id)
11+
12+
print(game.home_team + ' vs ' + game.away_team + ' (' + str(game.date) + ')')
13+
14+
types = ['home', 'away']
15+
for type in types:
16+
print(' ' + getattr(game, type + '_team') + ' Information:')
17+
team_players = getattr(players, type + '_players')
18+
team_coaches = getattr(players, type + '_coaches')
19+
20+
print(' Coaching Staff:')
21+
for coach in team_coaches:
22+
print(' {0}: {first} {last}'.format(rename(coach['position']), **coach))
23+
24+
print(' Starting Lineup:')
25+
starting_lineup = list(filter(lambda x: 'bat_order' in x.keys(), team_players))
26+
for player in sorted(starting_lineup, key=lambda k: k['bat_order']):
27+
print(' {bat_order}. {first} {last} ({game_position})'.format(**player))
28+
29+
print(' Umpires:')
30+
for umpire in players.umpires:
31+
print(' {0}: {first} {last}'.format(rename(umpire['position']), **umpire))
32+
33+
"""
34+
Twins vs Orioles (2017-07-09 13:10:00)
35+
Twins Information:
36+
Coaching Staff:
37+
Manager: Paul Molitor
38+
Hitting Coach: James Rowson
39+
Assistant Hitting Coach: Rudy Hernandez
40+
Pitching Coach: Neil Allen
41+
First Base Coach: Jeff Smith
42+
Third Base Coach: Gene Glynn
43+
Bench Coach: Joe Vavra
44+
Bullpen Coach: Eddie Guardado
45+
Major League Coach: Jeff Pickler
46+
Bullpen Catcher: Nate Dammann
47+
Starting Lineup:
48+
0. Kyle Gibson (P)
49+
1. Brian Dozier (2B)
50+
2. Robbie Grossman (DH)
51+
3. Max Kepler (RF)
52+
4. Miguel Sano (3B)
53+
5. Kennys Vargas (1B)
54+
6. Eddie Rosario (LF)
55+
7. Jorge Polanco (SS)
56+
8. Chris Gimenez (C)
57+
9. Zack Granite (CF)
58+
Orioles Information:
59+
Coaching Staff:
60+
Manager: Buck Showalter
61+
Hitting Coach: Scott Coolbaugh
62+
Assistant Hitting Coach: Howie Clark
63+
Pitching Coach: Roger McDowell
64+
First Base Coach: Wayne Kirby
65+
Third Base Coach: Bobby Dickerson
66+
Bench Coach: John Russell
67+
Bullpen Coach: Alan Mills
68+
Coach: Einar Diaz
69+
Starting Lineup:
70+
0. Ubaldo Jimenez (P)
71+
1. Seth Smith (RF)
72+
2. Manny Machado (3B)
73+
3. Jonathan Schoop (2B)
74+
4. Adam Jones (CF)
75+
5. Mark Trumbo (DH)
76+
6. Trey Mancini (1B)
77+
7. Hyun Soo Kim (LF)
78+
8. Caleb Joseph (C)
79+
9. Ruben Tejada (SS)
80+
Umpires:
81+
Home: Lance Barrett
82+
First: Bill Welke
83+
Second: Jim Reynolds
84+
Third: Sean Barber
85+
"""

mlbgame/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,12 @@ def teams():
274274
"""Return list of Info objects for each team"""
275275
return [mlbgame.info.Info(x) for x in mlbgame.info.team_info()]
276276

277+
277278
def disabled_list(team_id):
278279
"""Return Injury object that contains DL info for a team"""
279280
return mlbgame.injury.Injury(team_id)
281+
282+
283+
def players(game_id):
284+
"""Return list players/coaches/umpires for game matching the game id."""
285+
return mlbgame.game.Players(mlbgame.game.players(game_id))

mlbgame/data.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,18 @@ def get_overview(game_id):
6363
raise ValueError("Could not find a game with that id.")
6464

6565

66+
def get_players(game_id):
67+
"""Return the players file of a game with matching id."""
68+
year, month, day = get_date_from_game_id(game_id)
69+
try:
70+
print(GAME_URL.format(year, month, day, game_id, "players.xml"))
71+
return urlopen(GAME_URL.format(year, month, day,
72+
game_id,
73+
"players.xml"))
74+
except HTTPError:
75+
raise ValueError("Could not find a game with that id.")
76+
77+
6678
def get_properties():
6779
"""Return the current mlb properties file"""
6880
try:
@@ -75,4 +87,4 @@ def get_properties():
7587

7688
def get_date_from_game_id(game_id):
7789
year, month, day, _discard = game_id.split('_', 3)
78-
return year, month, day
90+
return int(year), int(month), int(day)

mlbgame/game.py

+55
Original file line numberDiff line numberDiff line change
@@ -321,3 +321,58 @@ def __init__(self, data):
321321
setattr(self, x, str(data[x]))
322322
element_list.append(x)
323323
self.elements = set(element_list)
324+
325+
def players(game_id):
326+
"""Gets player/coach/umpire information for the game with matching id."""
327+
# get data
328+
data = mlbgame.data.get_players(game_id)
329+
# parse data
330+
parsed = etree.parse(data)
331+
root = parsed.getroot()
332+
333+
output = {}
334+
output['game_id'] = game_id
335+
336+
# get player/coach data
337+
for team in root.findall('team'):
338+
type = team.attrib['type'] + "_team"
339+
# the type is either home_team or away_team
340+
output[type] = {}
341+
output[type]['players'] = []
342+
output[type]['coaches'] = []
343+
344+
for p in team.findall('player'):
345+
player = {}
346+
for key in p.keys():
347+
player[key] = p.get(key)
348+
output[type]['players'].append(player)
349+
350+
for c in team.findall('coach'):
351+
coach = {}
352+
for key in c.keys():
353+
coach[key] = c.get(key)
354+
output[type]['coaches'].append(coach)
355+
356+
# get umpire data
357+
output['umpires'] = []
358+
for u in root.find('umpires').findall('umpire'):
359+
umpire = {}
360+
for key in u.keys():
361+
umpire[key] = u.get(key)
362+
output['umpires'].append(umpire)
363+
364+
return output
365+
366+
class Players(object):
367+
"""Object to hold player/coach/umpire information for a game."""
368+
369+
def __init__(self, data):
370+
"""Creates an overview object that matches the corresponding info in `data`.
371+
`data` should be an dictionary of values.
372+
"""
373+
self.game_id = data['game_id']
374+
self.home_players = data['home_team']['players']
375+
self.home_coaches = data['home_team']['coaches']
376+
self.away_players = data['away_team']['players']
377+
self.away_coaches = data['away_team']['coaches']
378+
self.umpires = data['umpires']

0 commit comments

Comments
 (0)