Ejemplo n.º 1
0
def parse_shift(shift):
    """
    Parse shift for json
    
    :param shift: json for shift
    
    :return: dict with shift info
    """
    shift_dict = dict()

    name = shared.fix_name(' '.join([
        shift['firstName'].strip(' ').upper(),
        shift['lastName'].strip(' ').upper()
    ]))
    shift_dict['Player'] = name
    shift_dict['Player_Id'] = shift['playerId']
    shift_dict['Period'] = shift['period']
    shift_dict['Team'] = fix_team_tricode(shift['teamAbbrev'])

    # At the end of the json they list when all the goal events happened. They are the only one's which have their
    # eventDescription be not null
    if shift['eventDescription'] is None:
        shift_dict['Start'] = shared.convert_to_seconds(shift['startTime'])
        shift_dict['End'] = shared.convert_to_seconds(shift['endTime'])
        shift_dict['Duration'] = shared.convert_to_seconds(shift['duration'])
    else:
        shift_dict = dict()

    return shift_dict
Ejemplo n.º 2
0
def parse_event(event):
    """
    Parses a single event when the info is in a json format
    
    :param event: json of event 
    
    :return: dictionary with the info
    """
    play = dict()

    play['event_id'] = event['about']['eventIdx']
    play['period'] = event['about']['period']
    play['event'] = str(change_event_name(event['result']['eventTypeId']))
    play['seconds_elapsed'] = shared.convert_to_seconds(event['about']['periodTime'])

    # If there's a players key that means an event occurred on the play.
    if 'players' in event.keys():
        play['p1_name'] = shared.fix_name(event['players'][0]['player']['fullName'])
        play['p1_ID'] = event['players'][0]['player']['id']

        for i in range(len(event['players'])):
            if event['players'][i]['playerType'] != 'Goalie':
                play['p{}_name'.format(i + 1)] = shared.fix_name(event['players'][i]['player']['fullName'].upper())
                play['p{}_ID'.format(i + 1)] = event['players'][i]['player']['id']

        # Coordinates aren't always there
        try:
            play['xC'] = event['coordinates']['x']
            play['yC'] = event['coordinates']['y']
        except KeyError:
            play['xC'] = ''
            play['yC'] = ''

    return play
Ejemplo n.º 3
0
def analyze_shifts(shift, name, team, home_team, player_ids):
    """
    Analyze shifts for each player when using.
    Prior to this each player (in a dictionary) has a list with each entry being a shift.

    :param shift: info on shift
    :param name: player name
    :param team: given team
    :param home_team: home team for given game
    :param player_ids: dict with info on players
    
    :return: dict with info for shift
    """
    shifts = dict()

    regex = re.compile('\d+')  # Used to check if something contains a number

    shifts['Player'] = name.upper()
    shifts['Period'] = '4' if shift[1] == 'OT' else shift[1]
    shifts['Team'] = shared.TEAMS[team.strip(' ')]
    shifts['Home_Team'] = shared.TEAMS[home_team.strip(' ')]
    shifts['Start'] = shared.convert_to_seconds(shift[2].split('/')[0])
    shifts['Duration'] = shared.convert_to_seconds(shift[4].split('/')[0])

    # I've had problems with this one...if there are no digits the time is f****d up
    if regex.findall(shift[3].split('/')[0]):
        shifts['End'] = shared.convert_to_seconds(shift[3].split('/')[0])
    else:
        shifts['End'] = shifts['Start'] + shifts['Duration']

    try:
        if home_team == team:
            shifts['Player_Id'] = player_ids['Home'][name.upper()]['id']
        else:
            shifts['Player_Id'] = player_ids['Away'][name.upper()]['id']
    except KeyError:
        shifts['Player_Id'] = ''

    return shifts
Ejemplo n.º 4
0
def add_time(event_dict, event):
    """
    Fill in time and seconds elapsed
    
    :param event_dict: dict of parsed event stuff
    :param event: event info from pbp
    
    :return: None
    """
    event_dict['Time_Elapsed'] = str(event[3])

    if event[3] != '':
        event_dict['Seconds_Elapsed'] = shared.convert_to_seconds(event[3])
    else:
        event_dict['Seconds_Elapsed'] = ''
Ejemplo n.º 5
0
def parse_event(event):
    """
    Parse each event. In the string each field is separated by a '~'. 
    Relevant for here: The first two are the x and y coordinates. And the 4th and 5th are the time elapsed and period.
    
    :param event: string with info
    
    :return: return dict with relevant info
    """
    info = dict()
    fields = event.split('~')

    # Shootouts screw everything up so don't bother...coordinates don't matter there either way
    if fields[4] == '5':
        return None

    info['xC'] = float(fields[0])
    info['yC'] = float(fields[1])
    info['time_elapsed'] = shared.convert_to_seconds(fields[3])
    info['period'] = fields[4]
    info['event'] = event_type(fields[8].upper())

    return info
Ejemplo n.º 6
0
def parse_event(event, score, teams, date, game_id, players):
    """
    Parses a single event when the info is in a json format

    :param event: json of event 
    :param score: Current score of the game
    :param teams: Teams dict (id -> name)
    :param date: date of the game
    :param game_id: game id for game
    :param players: Dict of player ids to player names
    
    :return: dictionary with the info
    """
    play = dict()

    # Basic shit
    play['play_index'] = event['play_index']
    play['date'] = date
    play['game_id'] = game_id
    play['season'] = shared.get_season(date)
    play['period'] = event['time_interval']
    play['seconds_elapsed'] = shared.convert_to_seconds(event['clock_time_string']) if event['clock_time_string'] else None
    play['home_score'], play['away_score'] = score['home'], score['away']

    # If shootout go with 'play_by_play_string' field -> more descriptive
    play['event'] = event['play_type'] if event['play_type'] != "Shootout" else event['play_by_play_string'].strip()

    # Teams
    play['home_team'], play['away_team'] = teams['home']['name'], teams['away']['name']
    if event['play_summary']['off_team_id'] == teams['home']['id']:
        play['ev_team'] = teams['home']['name']
    else:
        play['ev_team'] = teams['away']['name']

    # Player Id
    play['p1_id'] = event.get('primary_player_id')
    play['away_goalie_id'] = event['play_actions'][0].get('away_team_goalie')
    play['home_goalie_id'] = event['play_actions'][0].get('home_team_goalie')

    play['away_goalie'] = players.get(int(play['away_goalie_id']) if play['away_goalie_id'] not in ['', None] else 0)
    play['home_goalie'] = players.get(int(play['home_goalie_id']) if play['home_goalie_id'] not in ['', None] else 0)

    # Event specific stuff
    if event['play_type'] == 'Faceoff':
        play['p2_id'] = event['play_summary'].get("loser_id")
    elif event['play_type'] == 'Penalty':
        # TODO: Format better?
        play['details'] = ",".join([str(event['play_summary'].get("infraction_type", " ")),
                                    str(event['play_summary'].get("penalty_type", " ")),
                                    str(event['play_summary'].get("penalty_minutes", " "))])
    elif event['play_type'] == "Goal":
        get_goal_players(play, event, players)
        play['p2_id'] = event['play_summary'].get("assist_1_id")
        play['p3_id'] = event['play_summary'].get("assist_2_id")

        # Update Score
        if event['play_summary']['off_team_id'] == teams['home']['id']:
            score['home'] += 1
        else:
            score['away'] += 1

    # Player Id's --> Player Names
    for num in range(1, 4):
        player_id = play.get('p{num}_id'.format(num=num), 0)
        # Control for None
        player_id = player_id if player_id else 0
        play['p{num}_name'.format(num=num)] = players.get(int(player_id))

    # Coords
    play['xC'] = event['play_summary'].get('x_coord')
    play['yC'] = event['play_summary'].get('y_coord')

    return play
Ejemplo n.º 7
0
def test_convert_to_seconds():
    """ Tests if it correctly converts minutes remaining to seconds elapsed"""
    assert shared.convert_to_seconds("8:33") == 513
    assert shared.convert_to_seconds("-16:0-") == "1200"