SHOW:
|
|
- or go back to the newest paste.
| 1 | import requests | |
| 2 | from bs4 import BeautifulSoup | |
| 3 | import re | |
| 4 | from operator import itemgetter | |
| 5 | ||
| 6 | r = requests.get('http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population')
| |
| 7 | ||
| 8 | soup = BeautifulSoup(r.text) | |
| 9 | ||
| 10 | states = [] | |
| 11 | ||
| 12 | for flag in soup.find_all("span", class_="flagicon"):
| |
| 13 | if len(states) > 51: | |
| 14 | break | |
| 15 | state = flag.next_sibling.string | |
| 16 | if state == 'District of Columbia': | |
| 17 | state = "Washington D.C" | |
| 18 | population = int(flag.parent.findNext('td').string.replace(',',''))
| |
| 19 | states.append((state, population),) | |
| 20 | ||
| 21 | - | print len(states) |
| 21 | + | |
| 22 | ||
| 23 | regex = r'>(?P<state>[\w\s.]+)</font></div></td></tr><tr><td></td><td class="default"><span class="comhead"><span id=score_[\d]+>(?P<score>[\d]*) point[s]?<' | |
| 24 | ||
| 25 | out = [] | |
| 26 | ||
| 27 | for match in re.findall(regex, r.text): | |
| 28 | for state in states: | |
| 29 | if state[0] == match[0]: | |
| 30 | out.append((state[0], float(match[1])/state[1]),) | |
| 31 | ||
| 32 | out = sorted(out, key=itemgetter(1), reverse=True) | |
| 33 | ||
| 34 | for r in range(len(out)): | |
| 35 | print "%-2d %-20s : %f" % (r+1, out[r][0], out[r][1]*1000000) |