2017-07-20 20 views
0

テーブルをこのようにするにはどうすればいいですか?batting gamelogs table - PythonとBeautifulSoupを使用するCSVファイルには?HTMLテーブルをCSVファイルに変換する

Rk、Gcar、Gtmなどと言う最初のヘッダーが必要で、テーブル内の他のヘッダー(季節の各月のヘッダー)は必要ありません。ここで

は私が持っているコードは、これまでです:

from bs4 import BeautifulSoup 
from urllib2 import urlopen 
import csv 

def stir_the_soup(): 
    player_links = open('player_links.txt', 'r') 
    player_ID_nums = open('player_ID_nums.txt', 'r') 
    id_nums = [x.rstrip('\n') for x in player_ID_nums] 
    idx = 0 
    for url in player_links: 
     print url 
     soup = BeautifulSoup(urlopen(url), "lxml") 
     p_type = "" 
     if url[-12] == 'p': 
      p_type = "pitching" 
     elif url[-12] == 'b': 
      p_type = "batting" 
     table = soup.find(lambda tag: tag.name=='table' and tag.has_attr('id') and tag['id']== (p_type + "_gamelogs")) 
     header = [[val.text.encode('utf8') for val in table.find_all('thead')]] 
     rows = [] 
     for row in table.find_all('tr'): 
      rows.append([val.text.encode('utf8') for val in row.find_all('th')]) 
      rows.append([val.text.encode('utf8') for val in row.find_all('td')]) 
     with open("%s.csv" % id_nums[idx], 'wb') as f: 
      writer = csv.writer(f) 
      writer.writerow(header) 
      writer.writerows(row for row in rows if row) 
     idx += 1 
    player_links.close() 

if __name__ == "__main__": 
    stir_the_soup() 

id_numsリストは別々のCSVファイルの名前として使用するために、各プレイヤーのID番号のすべてが含まれています。

各行について、一番左側のセルはタグであり、残りの行はタグです。ヘッダーに加えて、それをどのように1行に入れるのですか?

+0

パンダにはおそらくあなたが望む線に沿っている素晴らしい機能 'read_html'があります。 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html – dashiell

答えて

0

このコードは、私はあなたが望む考えるものである、あなたの統計の大きなテーブルを取得します。 lxmlbeautifulsoup4pandasがインストールされていることを確認してください。

ここには最初の5行の出力があります。

df[4].head(5) 
    Rk Gcar Gtm Date Tm Unnamed: 5 Opp Rslt Inngs PA ... CS BA OBP SLG OPS BOP aLI WPA RE24 Pos 
0 1 66 2 (1) Apr 6 ARI NaN SDP L,3-6 7-8 1 ... 0 1.000 1.000 1.000 2.000 9 .94 0.041 0.51 PH 
1 2 67 3 Apr 7 ARI NaN SDP W,5-3 7-8 1 ... 0 .500 .500 .500 1.000 9 1.16 -0.062 -0.79 PH 
2 3 68 4 Apr 9 ARI NaN PIT W,9-1 8-GF 1 ... 0 .667 .667 .667 1.333 2 .00 0.000 0.13 PH SS 
3 4 69 5 Apr 10 ARI NaN PIT L,3-6 CG 4 ... 0 .500 .429 .500 .929 2 1.30 -0.040 -0.37 SS 
4 5 70 7 (1) Apr 13 ARI @ LAD L,5-9 6-6 1 ... 0 .429 .375 .429 .804 9 1.52 -0.034 -0.46 PH 

このDATAFRAME内の特定の列を選択するために:私はあなたの正確なendgoalが何であるかを知らないとあなたは少しそれをきれいにする必要があるかもしれませんdf[4]['COLUMN_NAME_HERE'].head(5)

例:df[4]['Gcar']

また、やっている場合df[4]あなたはいつも別のデータフレームに切り替えることができます。df2=df[4]

0
import pandas as pd 
from bs4 import BeautifulSoup 
import urllib2 

url = 'https://www.baseball-reference.com/players/gl.fcgi?id=abreuto01&t=b&year=2010' 
html=urllib2.urlopen(url) 

bs = BeautifulSoup(html,'lxml') 

table = str(bs.find('table',{'id':'batting_gamelogs'})) 

dfs = pd.read_html(table) 

これは、このようなものには非常に便利なパンダを使用しています。それはまた、他の操作を行うためにかなり合理的なフォーマットにしています。

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html

+0

その後、read_html()がそれをデータフレームのタプルに変換するので、それを独自のCSVファイルに変換するにはどうすればよいですか? –

関連する問題