python - Associating the correct teams with the correct score values -


i have code outputs teams , score values (without spaces) page http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01.

from bs4 import beautifulsoup urllib.request import urlopen  url = urlopen("http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01")  content = url.read()  soup = beautifulsoup(content)  listnames = '' listscores = ''  table in soup.find_all('table', class_='scores'):     row in table.find_all('tr'):         cell in row.find_all('td', class_='yspscores'):             if cell.text.isdigit():                 listscores += cell.text         cell in row.find_all('td', class_='yspscores team'):             listnames += cell.text  print (listnames) print (listscores) 

the problem can't solve don't quite understand how python can use extracted information , give correct teams correct integer values in format this:

team x: 1, 5, 11. 

the issue website scores under same class; tables under same class. thing different href.

when want associate values names, dict way go. here's modification of code demonstrate principle:

from bs4 import beautifulsoup urllib.request import urlopen  url = urlopen('http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01')  content = url.read()  soup = beautifulsoup(content)  results = {}  table in soup.find_all('table', class_='scores'):     row in table.find_all('tr'):         scores = []         name = none         cell in row.find_all('td', class_='yspscores'):             link = cell.find('a')             if link:                 name = link.text             elif cell.text.isdigit():                 scores.append(cell.text)         if name not none:             results[name] = scores  name, scores in results.items():     print('%s: %s' % (name, ', '.join(scores))) 

... gives output when run:

$ python3 get_scores.py st. louis: 1, 2, 1 san jose: 0, 3, 0 colorado: 0, 0, 2 dallas: 0, 0, 0 new jersey: 0, 1, 0 ny islanders: 2, 0, 1 nashville: 0, 0, 2, 0 minnesota: 0, 1, 0 detroit: 1, 2, 0 ny rangers: 1, 1, 2 anaheim: 0, 3, 1 winnipeg: 2, 0, 0 chicago: 1, 1, 0, 0 calgary: 0, 0, 1 vancouver: 0, 1, 1 edmonton: 3, 0, 1 montreal: 1, 1, 2 carolina: 1, 0, 0 

apart use of dictionary, other significant change we're checking existence of a element team's name, rather additional team class. that's stylistic choice, me code seems more expressive way.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -