develope_kkyu
[Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기 - 4 본문
https://developerkkyu37.tistory.com/72
[Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기 - 3
https://developerkkyu37.tistory.com/70 [Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기 - 2 https://developerkkyu37.tistory.com/69 [Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기(배포) - 1 MLB-StatsAPI와 streamlit 라
developerkkyu37.tistory.com
[
0:{
"game_id":662033
"game_datetime":"2022-08-31T19:45:00Z"
"game_date":"2022-08-31"
"game_type":"R"
"status":"Final"
"away_name":"San Diego Padres"
"home_name":"San Francisco Giants"
"away_id":135
"home_id":137
"doubleheader":"N"
"game_num":1
"home_probable_pitcher":"Alex Wood"
"away_probable_pitcher":"Joe Musgrove"
"home_pitcher_note":""
"away_pitcher_note":""
"away_score":5
"home_score":4
"current_inning":9
"inning_state":"Bottom"
"venue_id":2395
"venue_name":"Oracle Park"
"national_broadcasts":[]
"series_status":"SD wins 3-0"
"winning_team":"San Diego Padres"
"losing_team":"San Francisco Giants"
"winning_pitcher":"Joe Musgrove"
"losing_pitcher":"Alex Wood"
"save_pitcher":"Josh Hader"
"summary":"2022-08-31 - San Diego Padres (5) @ San Francisco Giants (4) (Final)"
}
]
오늘의 경기정보를 가져올 수 있으니 홈팀, 원정팀, 스코어를 보여줄 수 있다.
먼저 팀 이름을 가져온다.
away = scores[0]['away_name']
home = scores[0]['home_name']
팀이름이 영어로 나오다보니 한글로 바꾸고 싶었다. 그래서 팀이름을 한글로 바꾸는 함수를 만들어주었다.
def hanguel(team):
if team == "Atlanta Braves":
name = '애틀랜타'
if team == 'Miami Marlins':
name = '마이애미'
if team == 'New York Mets':
name = '뉴욕 메츠'
if team == "Philadelphia Phillies":
name = '필라델피아'
if team == 'Washington Nationals':
name = '워싱턴'
if team == 'Chicago Cubs':
name = '시카고 컵스'
if team == "Cincinnati Reds":
name = '신시내티'
if team == "Milwaukee Brewers":
name = '밀워키'
if team == "Pittsburgh Pirates":
name = '피츠버그'
if team == "St. Louis Cardinals":
name = '세인트루이스'
if team == "Arizona Diamondbacks":
name = '애리조나'
if team == "Colorado Rockies":
name = '콜로라도'
if team == "Los Angeles Dodgers":
name = 'LA다저스'
if team == "San Diego Padres":
name = '샌디에이고'
if team == "San Francisco Giants":
name = '샌프란시스코'
if team == "Baltimore Orioles":
name = '볼티모어'
if team == "Boston Red Sox":
name = '보스턴'
if team == "New York Yankees":
name = '뉴욕 양키스'
if team == "Tampa Bay Rays":
name = '템파베이'
if team == "Toronto Blue Jays":
name = '토론토'
if team == "Chicago White Sox":
name = '시카고W'
if team == "Cleveland Guardians":
name = '클리블랜드'
if team == "Detroit Tigers":
name = '디트로이트'
if team == "Kansas City Royals":
name = '캔자스시티'
if team == "Minnesota Twins":
name = '미네소타'
if team == "Houston Astros":
name = '휴스턴'
if team == "Los Angeles Angels":
name = 'LA에인절스'
if team == "Oakland Athletics":
name = '오클랜드'
if team == "Seattle Mariners":
name = '시애틀'
if team == "Texas Rangers":
name = '텍사스'
return name
함수 적용
away_h = hanguel(away)
home_h = hanguel(home)
스코어도 가져와준다.
away_score = str(scores[0]['away_score'])
home_score = str(scores[0]['home_score'])
출력
st.title(away_h + away_score + " " + home_score + home_h)
야구 경기 결과를 보면 항상 라인스코어가 나온다.
mlb-statsapi도 물론 라인스코어를 보여줄 수 있다. 하지만 문자열로 나와 조금 불편하다.
linescore = statsapi.linescore(game_id)
그래서 split()함수를 써서 단어단위로 나누고 데이터프레임에 넣어주려고 했다.
linescore = statsapi.linescore(game_id)
line = linescore.split("\n")
line1 = line[0].split()
line2 = line[1].split()
line3 = line[2].split()
그런데 Blue Jays나 Red Sox, White Sox의 띄어쓰기가 되어있어서 두 단어로 나뉘는 문제가 있어서 두 단어를 삭제하고 다시 합쳐서 삽입해주었다.
def insert(line):
if line[0] == 'Red':
del line[1]
del line[0]
line.insert(0, 'RedSox')
elif line[0] == 'White':
del line[1]
del line[0]
line.insert(0, 'WhiteSox')
elif line[0] == 'Blue':
del line[1]
del line[0]
line.insert(0, 'BlueJays')
return line
line2 = insert(line2)
line3 = insert(line3)
또다시 문제가 10회 이후 연장경기가 있을 때 101112 이런식으로 붙어나오는 현상이 있었다. 그래서 2글자씩 나눠서 공백을 주고 리스트를 만들어 그 자리에 삽입해주는 방법을 썼다.
if line1[10] != 'R':
l10 = line1[10]
li = ' '.join([l10[i:i+2] for i in range(0, len(l10), 2)])
l10 = li.split(' ')
del line1[10]
for a in range(int(l10[0]), int(l10[0])+int(len(l10))):
line1.insert(a, l10[a-10])
데이터프레임을 만들고 각 라인에 대한 리스트를 행삽입해주었다.
df_score = pd.DataFrame(columns=line1)
df_score.loc[0] = line2
df_score.loc[1] = line3
df_score = df_score.set_index('Final')
st.write(df_score)
총 코드
scores = statsapi.schedule(start_date=date,team=team_id)
try:
game_id = scores[0]['game_id']
# 라인스코어
linescore = statsapi.linescore(game_id)
line = linescore.split("\n")
line1 = line[0].split()
line2 = line[1].split()
line3 = line[2].split()
def insert(line):
if line[0] == 'Red':
del line[1]
del line[0]
line.insert(0, 'RedSox')
elif line[0] == 'White':
del line[1]
del line[0]
line.insert(0, 'WhiteSox')
elif line[0] == 'Blue':
del line[1]
del line[0]
line.insert(0, 'BlueJays')
return line
line2 = insert(line2)
line3 = insert(line3)
if line1[10] != 'R':
l10 = line1[10]
li = ' '.join([l10[i:i+2] for i in range(0, len(l10), 2)])
l10 = li.split(' ')
del line1[10]
for a in range(int(l10[0]), int(l10[0])+int(len(l10))):
line1.insert(a, l10[a-10])
df_score = pd.DataFrame(columns=line1)
df_score.loc[0] = line2
df_score.loc[1] = line3
df_score = df_score.set_index('Final')
away = scores[0]['away_name']
home = scores[0]['home_name']
away_h = hanguel(away)
home_h = hanguel(home)
away_score = str(scores[0]['away_score'])
home_score = str(scores[0]['home_score'])
st.title(away_h + away_score + " " + home_score + home_h)
st.write(df_score)
except:
pass
'Python' 카테고리의 다른 글
[Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기 - 6 (0) | 2023.03.06 |
---|---|
[Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기 - 5 (0) | 2023.03.04 |
[Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기 - 3 (0) | 2023.02.26 |
[오류 해결] TypeError: unsupported operand type(s) for &: ‘str’ and ‘str’ (0) | 2023.02.19 |
[Python] MLB-StatsAPI를 이용한 mlb 기록 사이트 만들기 - 2 (0) | 2023.02.11 |