2014-10-12 2 views
0

다음 데이터 프레임이 있습니다. 그것은 imdb에서 온 것입니다. 내가해야 할 일은 5 점 미만으로 100,000 표 이상을받는 영화를 추출하는 것입니다. 내 문제는을 투표하는 에 대한 마지막 코드 줄이 실제로 무엇인지 이해하지 못한다는 것입니다.파이썬 데이터 프레임 문제

# two lists, one for movie data, the other of vote data 
movie_data=[] 
vote_data=[] 
# this will do some reformating to get the right unicode escape for 
hexentityMassage = [(re.compile('&#x([^;]+);'), lambda m: '&#%d;' % int(m.group(1), 16))] # converts XML/HTML entities into unicode string in Python 
for i in range(20): 
    next_url = 'http://www.imdb.com/search/title?sort=num_votes,desc&start=%d&title_type=feature&year=1950,2012'%(i*50+1) 
    r = requests.get(next_url) 
    bs = BeautifulSoup(r.text,convertEntities=BeautifulSoup.HTML_ENTITIES,markupMassage=hexentityMassage) 
    # movie info is found in the table cell called 'title' 
    for movie in bs.findAll('td', 'title'): 
     title = movie.find('a').contents[0].replace('&','&') #get '&' as in 'Batman & Robin' 
     genres = movie.find('span', 'genre').findAll('a') 
     year = int(movie.find('span', 'year_type').contents[0].strip('()')) 
     genres = [g.contents[0] for g in genres] 
     runtime = movie.find('span', 'runtime').contents[0] 
     rating = float(movie.find('span', 'value').contents[0]) 
     movie_data.append([title, genres, runtime, rating, year]) 
    # rating info is found in a separate cell called 'sort_col' 
    for voting in bs.findAll('td', 'sort_col'): 
     vote_data.append(int(voting.contents[0].replace(',',''))) 
+2

당신은이'pandas' 태그를 붙였습니다 만,이 코드 스 니펫에서 이것을 사용하지 않는 것처럼 보입니다. 이것은 주로'BeautifulSoup'입니다. – DSM

+0

질문에 관련이 없으므로 첫 번째 루프를 포함시킨 이유는 무엇입니까? – stark

답변

0

귀하의 문제는 당신이 속성 sort_col이있는 모든 td 태그를 통해 루핑 여기

for voting in bs.findAll('td', 'sort_col'): 
    vote_data.append(int(voting.contents[0].replace(',',''))) 

이 조각입니다. 이 경우 그들은 class="sort_col"입니다. 두 번째 줄에서

,

  • 당신은 voting.contents에 의해 반환되는리스트의 첫 번째 요소의 ','''와 (빈 문자열)을 대체하고있다.
  • int으로 전송하십시오.
  • 다음에이를 vote_data에 붙입니다. 나는 이것을 어기면

, 그것은 루프의 값이 더 이해를 얻을 수

for voting in bs.findAll('td', 'sort_col'): 
    # voting.contents returns a list like this [u'377,936'] 
    str_vote = voting.contents[0] 
    # str_vote will be '377,936' 
    int_vote = int(str_vote.replace(',', '')) 
    # int_vote will be 377936 
    vote_data.append(int_vote) 

인쇄, 이렇게 될 것입니다. 질문에 태그를 달았 으면 좋은 대답을 빨리 얻을 수 있습니다.

관련 문제