Skip to content

Instantly share code, notes, and snippets.

@davidair
Last active December 8, 2017 20:24
Show Gist options
  • Save davidair/1626c15d9b909bc0b8dd3646887853d4 to your computer and use it in GitHub Desktop.
Save davidair/1626c15d9b909bc0b8dd3646887853d4 to your computer and use it in GitHub Desktop.
Convert Wikipedia Chess Diagram to FEN
#!/usr/bin/python
# Copyright 2017 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
if len(sys.argv) < 2:
print 'usage: wikipedia_to_fen.py diagram.txt'
exit
with open(sys.argv[1]) as input:
content = input.readlines()
rows = []
for line in content:
entry = line.strip().split('|')
if len(entry) == 9:
rows.append(entry)
fen = []
for row in rows:
spaces = 0
for square in row[1:]:
if square.strip() == '':
spaces += 1
else:
if spaces > 0:
fen.append(str(spaces))
spaces = 0
piece = square[0]
if square[1] == 'l':
piece = piece.upper()
fen.append(piece)
if spaces > 0:
fen.append(str(spaces))
fen.append('/')
result = ''.join(fen[:-1]) + ' w - -'
print result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment