Skip to content

Instantly share code, notes, and snippets.

@HyShai

HyShai/scores.py Secret

Created Nov 16, 2014
Embed
What would you like to do?
scores.py
import re
scores = [[u'Orlando 81 Washington 90 (3:55 IN 4TH)'], [u'Atlanta 59 Cleveland 87 (3:51 IN 3RD)'], [u'Utah 62 Toronto 69 (3:59 IN 3RD)'], [u'Indiana 46 Chicago 42 (0:03 IN 2ND)'], [u'Detroit 50 Memphis 51 (0:18 IN 2ND)'], [u'Minnesota 22 Dallas 28 (0:00 IN 1ST)'], [u'Brooklyn at Portland (10:00 PM ET)'], [u'San Antonio at Sacramento (10:00 PM ET)'], [u'Charlotte at Golden State (10:30 PM ET)'], [u'Phoenix at LA Clippers (10:30 PM ET)']]
for score in scores:
print score
print re.sub('([a-zA-Z^ ]+?)(\\d+|at)\\s+?([a-zA-Z^ ]+?)(\\d+)?\\s+?(\\(.+\\))\\s+?', 'whatever replacment', score[0])
@cclauss

This comment has been minimized.

Copy link

@cclauss cclauss commented Nov 16, 2014

Here is an alternate way to represent your scores data:

scores = '''Orlando 38   Washington 46 (1:36 IN 2ND) 
Atlanta 25   Cleveland 37 (0:28 IN 1ST) 
Utah 25   Toronto 23 (0:00 IN 1ST) 
Indiana at Chicago (8:00 PM ET) 
Detroit at Memphis (8:00 PM ET) 
Minnesota at Dallas (8:30 PM ET) 
Brooklyn at Portland (10:00 PM ET) 
San Antonio at Sacramento (10:00 PM ET) 
Charlotte at Golden State (10:30 PM ET) 
Phoenix at LA Clippers (10:30 PM ET)'''

for score in scores.splitlines():
    print(score)
    # ...
@HyShai

This comment has been minimized.

Copy link
Owner Author

@HyShai HyShai commented Nov 16, 2014

@cclauss thanks! That is nicer. In practice though I'm getting the data from parsing a query string using the urllib.parse_qs method which returns an array for me. But for a contrived example your approach is easier to read. Thanks for the tip

@cclauss

This comment has been minimized.

Copy link

@cclauss cclauss commented Nov 16, 2014

A non-regex approach...

for score in scores.splitlines():
    print(score)
    teams, _, times = score.strip().rstrip(')').partition('(')
    if ' at ' in teams:
        away_team, home_team = teams.strip().split(' at ')
        away_score, home_score = 'at', ''
    else:
        away_team, home_team = teams.strip().split('  ')
        away_team, away_score = away_team.rsplit()
        home_team, home_score = home_team.rsplit()
    print(away_team, away_score, home_team, home_score, times)
    print('=' * 5)
print('=' * 15)
@HyShai

This comment has been minimized.

Copy link
Owner Author

@HyShai HyShai commented Nov 16, 2014

@cclaus - hmmm interesting - that's definitely more readable than my regex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment