import pgn
import openpyxl
import os
pgn_text = open('ChessCom_gmwso_202012.pgn').read()
dates = []
welo = []
belo = []
white = []
black = []
whiteLong = []
blackLong = []
def getValues(file):
test_str = file
test_date = "[Date"
res1 = [i for i in range(len(test_str)) if test_str.startswith(test_date, i)]
test_welo = "[WhiteElo"
res2 = [i for i in range(len(test_str)) if test_str.startswith(test_welo, i)]
test_belo = "[BlackElo"
res3 = [i for i in range(len(test_str)) if test_str.startswith(test_belo, i)]
test_white = "[White "
res4 = [i for i in range(len(test_str)) if test_str.startswith(test_white, i)]
test_black = "[Black "
res5 = [i for i in range(len(test_str)) if test_str.startswith(test_black, i)]
for i in res1:
dates.append(test_str[i+7:i+17])
for i in res2:
welo.append(test_str[i+11:i+15])
for i in res3:
belo.append(test_str[i+11:i+15])
for i in res4:
whiteLong.append(test_str[i+8:i+43]) //The max length of a nickname in chess.com is 35 characters
for i in res5:
blackLong.append(test_str[i+8:i+43])
for value in whiteLong:
posClose = value.find("]")
white.append(value[0:posClose-1])
for value in blackLong:
posClose = value.find("]")
black.append(value[0:posClose-1])
def generateExcel(dates,welo,belo,white,black):
file = 'chess_games.xlsx'
if os.path.isfile(file):
wb = openpyxl.load_workbook(filename=file)
else:
wb = openpyxl.Workbook()
ws = wb["chess_games"]
for k in range (len(dates)):
ws['A'+str(k+1)] = dates[k]
for k in range (len(welo)):
ws['B'+str(k+1)] = welo[k]
for k in range (len(belo)):
ws['C'+str(k+1)] = belo[k]
for k in range (len(white)):
ws['D'+str(k+1)] = white[k]
for k in range (len(black)):
ws['E'+str(k+1)] = black[k]
wb.save(file)
getValues(pgn_text)
generateExcel(dates,welo,belo,white,black)