''' Created on Feb 10, 2019 @author: Brett Paufler Copyright Brett Paufler 1-0 White Wins 0-1 Black Wins Given one or more pgn chess move files outputs csv of: first move who won count of that type So, it extracts a popularity of moves from chess game files This only extracts the first move. I never went deeper than that. ''' from os import listdir from collections import defaultdict #Default Dictionary Used as a Counter first_move_results = defaultdict(int) #ALL pgn files in input directory pgn_files = [str('./input/' + f) for f in listdir('./input/') if f.endswith('.pgn')] #Loop over each file for pgn_file in pgn_files: print('Working On: ', pgn_file, sep=' ') #So, do this for each file with open(pgn_file, 'r') as f: winner = '' all_moves = '' first_move = '' line_tag = False line_blank = False line_move = False line = f.readline() while line: #Ingore All Tags #Move to Next if line.startswith('['): #print(line) #Finds the Winner if line.startswith('[Result "'): win_raw = line.split('"')[1] if win_raw == '1-0': winner = 'White' elif win_raw == '0-1': winner = 'Black' elif win_raw == '1/2-1/2': winner = 'Tie' elif win_raw == '*': winner = '*' else: assert True == False elif line.strip(): all_moves += ' ' + line.strip() all_moves = all_moves.strip() else: if all_moves: #Add Results to Dictionary first_move = all_moves.split(' ')[0][2:] game_key = first_move + ',' + winner first_move_results[game_key] += 1 #Clear it all Out all_moves = '' first_move = '' winner = '' #Next Loop of Input File line = f.readline() #first_move_results['test'] += 1 OUTPUT_FILE = './output/first_move_results.csv' with open(OUTPUT_FILE, 'w') as f: for k,v in first_move_results.items(): text_out = k + ',' + str(v) + '\n' print(text_out) f.write(text_out) print('Terminated As Expected')