Использование необработанного ввода для индексации xarray DataArrays из наборов данных

В коде есть так много дублирования. Старайтесь избегать программирования копирования и вставки.

При этом вы можете сделать список из тех же элементов: ['foo'] * 3 дает ['foo', 'foo', 'foo']. Это удобно для названия команды, которое одинаково для всех членов команды.

Вы можете использовать zip() и writerows() для записи всех списков в CSV в одной строке кода.

import requests
import csv
from bs4 import BeautifulSoup

page = requests.get('http://m.rays.mlb.com/roster/')
soup = BeautifulSoup(page.text, 'html.parser')

soup.find(class_='nav-tabset-container').decompose()
soup.find(class_='column secondary span-5 right').decompose()

roster = soup.find(class_='layout layout-roster')
names = [n.contents[0] for n in roster.find_all('a')]
number = [n.contents[0] for n in roster.find_all('td', index='0')]
handedness = [n.contents[0] for n in roster.find_all('td', index='3')]
height = [n.contents[0] for n in roster.find_all('td', index='4')]
weight = [n.contents[0] for n in roster.find_all('td', index='5')]
DOB = [n.contents[0] for n in roster.find_all('td', index='6')]
team = [soup.find('meta',property='og:site_name')['content']] * len(names)

with open('MLB_Active_Roster.csv', 'w', newline='') as fp:
    f = csv.writer(fp)
    f.writerow(['Name','Number','Hand','Height','Weight','DOB','Team'])
    f.writerows(zip(names, number, handedness, height, weight, DOB, team))
0
задан Luke Grant 20 January 2019 в 09:20
поделиться