我已经完成了这个并且测试打印了整个脚本,并且在所请求的季节中每个游戏都经历了每次击球。 Try:
所处的唯一原因是因为全明星中断的天数中断。当我在底部没有writer.writerow
的情况下打印时,它可以正常工作。一旦我取消注释它,并尝试写入csv Prints
一行,我不写。我已经在Try:
内尝试了写入csv而我已经知道我应该定义函数来清理它,但我仍然在学习正确的写作技巧。不知道我错过了什么,或者没有适当的间隔......另一组眼睛会很棒。
请求编辑 短版
import csv
import requests
import datetime
from pprint import pprint
import pendulum
## MLB SEASON DATES
## 2016 (4-3-16 to 10-2-16) # 2017 (4-2-17 to 10-1-17) # 2018 (3-29-18 to 9-30-18)
try:
## Write to csv
outfile = open('ALL_PA_LOG_2016.csv',"w",newline='')
writer = csv.writer(outfile)
writer.writerow(["gamepk", "day", "month", "year", "gamedate", "res_event", "des"])
# Put in Start date and End Date Below
start = pendulum.datetime(2016, 4, 3)
end = pendulum.datetime(2016, 10, 2)
period = pendulum.period(start, end)
for dt in period.range('days'):
day = dt.format('DD')
month = dt.format('MM')
year = dt.format('YYYY')
## Because there is the ALL STAR BREAK, Once these dates hit the break
## there is no regular season game scheduled so we get a KeyError and TypeError.
## A Try statement was the first idea I had, could be better but this works.
req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') #
get_gameIds = req.json()['data']['games']['game']
for gameId in get_gameIds:
gamepk = gameId['game_pk']
#GET GAMES BY GAMEPK WORKING GAME 530309
req = requests.get('https://statsapi.mlb.com/api/v1.1/game/' + str(gamepk) + '/feed/live?language=en') # ' + str(gamepk) + ' 530302
at_bat_log = req.json()['liveData']['plays']['allPlays']
### GET DATE
game_data = req.json()['gameData']
gamedate = game_data['datetime']['originalDate']
### GET PARK & TEAMS
teams = game_data['teams']
home_team = teams['home']
park = home_team['abbreviation']
away = teams['away']['abbreviation']
home = home_team['abbreviation']
for keys in at_bat_log:
# Result Keys
result = keys['result']
res_type = result['type']
res_event = result['event']
des = result['description']
rbi = result['rbi']
# End Result Keys
# About Keys
about = keys['about']
topbot = about['halfInning']
if topbot == "bottom":
topbot = "B"
if topbot == "top":
topbot = "T"
inn = about['inning']
inning = str(topbot) + str(inn)
print(gamepk, day, month, year, gamedate, res_event, des)
## writer.writerow[(gamepk, day, month, year, gamedate, res_event, des)]
except(KeyError,TypeError):
pass
完整脚本
import csv
import requests
import datetime
from pprint import pprint
import pendulum
## MLB SEASON DATES
## 2016 (4-3-16 to 10-2-16) # 2017 (4-2-17 to 10-1-17) # 2018 (3-29-18 to 9-30-18)
try:
## Write to csv
outfile = open('ALL_PA_LOG_2016.csv',"w",newline='')
writer = csv.writer(outfile)
writer.writerow(["gamepk", "year", "gamedate", "batter", "res_event", "inning", "pitcher_team", "pitcher",
"pa", "ab", "h", "single", "double", "triple", "hr", "bb", "tb", "gidp", "hbp", "sh", "sf", "ibb", "k", "gb",
"fb", "line", "rbi", "des"])
# Put in Start date and End Date Below
start = pendulum.datetime(2016, 4, 3)
end = pendulum.datetime(2016, 10, 2)
period = pendulum.period(start, end)
for dt in period.range('days'):
day = dt.format('DD')
month = dt.format('MM')
year = dt.format('YYYY')
## Because there is the ALL STAR BREAK, Once these dates hit the break
## there is no regular season game scheduled so we get a KeyError and TypeError.
## A Try statement was the first idea I had, could be better but this works.
req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') #
get_gameIds = req.json()['data']['games']['game']
for gameId in get_gameIds:
gamepk = gameId['game_pk']
#GET GAMES BY GAMEPK WORKING GAME 530309
req = requests.get('https://statsapi.mlb.com/api/v1.1/game/' + str(gamepk) + '/feed/live?language=en') # ' + str(gamepk) + ' 530302
at_bat_log = req.json()['liveData']['plays']['allPlays']
### GET DATE
game_data = req.json()['gameData']
gamedate = game_data['datetime']['originalDate']
### GET PARK & TEAMS
teams = game_data['teams']
home_team = teams['home']
park = home_team['abbreviation']
away = teams['away']['abbreviation']
home = home_team['abbreviation']
for keys in at_bat_log:
# Result Keys
result = keys['result']
res_type = result['type']
res_event = result['event']
des = result['description']
rbi = result['rbi']
# End Result Keys
# About Keys
about = keys['about']
topbot = about['halfInning']
if topbot == "bottom":
topbot = "B"
if topbot == "top":
topbot = "T"
inn = about['inning']
inning = str(topbot) + str(inn)
# End About Keys
# Start Count Keys
count = keys['count']
strike = count['strikes']
balls = count['balls']
pitch_total = int(str(strike)) + int(str(balls))
total_count = str(pitch_total) + '(' + str(balls) + '-' + str(strike) + ')'
# End Count Keys
# Start Matchup Keys
matchup = keys['matchup']
batter = matchup['batter']['fullName']
bats = matchup['batSide']['code']
pitcher = matchup['pitcher']['fullName']
throws = matchup['pitchHand']['code']
# End Matchup Keys
# Runners On Start
runnerIndex = keys['runnerIndex']
runnersOn = len(runnerIndex)
# Runners On End
# Play Events Start
playEvents = keys['playEvents']
for event in playEvents:
e_type = event['type']
# Play Events End
# Set up Stats
pa = 1 # Plate appearance always 1
ab = 0 #
h = 0 # hit. Add 1 after 1b, 2b, 3b, hr
single = 0 # Single
double = 0 # Double
triple = 0 # Triple
hr = 0 # Home Run
bb = 0 # Walk
tb = 0 # total bases
gidp = 0 # Grounded Into DP
hbp = 0 # Hit By Pitch
sh = 0 # Sac Bunt
sf = 0 # Sac Fly
ibb = 0 # Intent Walk
k = 0 # Strikeout
gb = 0 # Groundout
fb = 0 # Pop Out and Flyout
line = 0 # Lineout
fo = 0 # Forceout not credited with hit for fielders choice.
batter_team = " "
pitcher_team = " "
if res_event == "Single":
single += 1
h += 1
ab += 1
tb += 1
elif res_event == "Double":
double += 1
h += 1
ab += 1
tb += 2
elif res_event == "Triple":
triple += 1
h += 1
ab += 1
tb += 3
elif res_event == "Home Run":
hr += 1
h += 1
ab += 1
tb += 4
elif res_event == "Walk":
bb += 1
elif res_event == "Grounded Into DP":
gidp += 1
ab += 1
elif res_event == "Hit By Pitch":
hbp += 1
elif res_event == "Sac Bunt":
sh += 1
elif res_event == "Sac Fly":
sf += 1
elif res_event == "Intent Walk":
ibb += 1
elif res_event == "Strikeout":
k += 1
ab += 1
elif res_event == "Groundout":
gb += 1
ab += 1
elif res_event == "Flyout":
fb += 1
ab += 1
elif res_event == "Pop Out":
fb += 1
ab += 1
elif res_event == "Lineout":
line += 1
ab += 1
elif res_event == "Field Error":
ab += 1
elif res_event == "Fielders Choice Out":
ab += 1
elif res_event == "Forceout":
ab += 1
elif res_event == "Runner Out":
ab += 1
elif res_event == "Runner Out" and e_type == "pickoff":
pa = 0
elif topbot == "T":
batter_team = str(away)
elif topbot == "B":
batter_team = str(home)
elif topbot == "T":
pitcher_team = str(home)
elif topbot == "B":
pitcher_team = str(away)
print(gamepk, year, gamedate, batter, res_event, inning, pitcher, pa, ab, h, single, double,
triple, hr, bb, tb, gidp, hbp, sh, sf, ibb, k, gb, fb, line, rbi, des)
writer.writerow[(gamepk, year, gamedate, batter, res_event, inning, pitcher_team, pitcher,
pa, ab, h, single, double, triple, hr, bb, tb, gidp, hbp, sh, sf, ibb, k, gb,
fb, line, rbi, des)]
except(KeyError,TypeError):
pass
答案 0 :(得分:1)
假设正确打印,则应进行以下更改:
row = [gamepk, year, gamedate, batter, res_event, inning, pitcher, pa, ab, h, single, double,
riple, hr, bb, tb, gidp, hbp, sh, sf, ibb, k, gb, fb, line, rbi, des]
print(*row)
writer.writerow(row)
您的代码语法错误,即
writer.writerow[(......)]