[英]Exporting Chess moves and images into HTML or CSV format
我已经使用帖子( 使用 python-chess 库打印单个动作)来获取棋盘的单个动作并显示图像。 请参阅下面的代码。
import chess
from io import StringIO
import chess.pgn
#create a virtual board
board = chess.Board()
#Paste PGN data
pgn_string = """
1 e4 e6 2 d4 c6 3 Nf3 Nf6 4 Bg5 h6 5 Bf4 Na6 6 Bc4 d5 7 Bd3 Nxe4 8 O-O Nb4 9 Ne5 a5
10 Qg4 f5 11 Qg6+ Ke7 12 Qf7+ Kd6 13 Nc4#
"""
# Converting the string into StringIO object
pgn = StringIO(pgn_string)
# Reading the game
game = chess.pgn.read_game(pgn)
#Printing and displaying the moves in algebraic notation
for move in game.mainline_moves():
print(board.san(move))
board.push(move)
display(board)
我能够在 jupyter 中获得 output(见下图)的每个动作及其相应的棋盘图像(在 jupyter 中的滚动 window 内)
我试图弄清楚上述数据(即单个动作及其图像)是否可以导出为 HTML 或 CSV 格式,以便我可以分析这些动作,因为在 jupyter 中很难分析。 提前致谢
命令board.san(move)
将当前移动作为文本提供,您可以将其保留在列表中以便以后保存。
在文档中我发现 function chess.svg.board()生成字符串SVG image
- 你可以保存在文件中使用标准open()
, write()
close()
每个浏览器都可以在 HTML 中显示图像svg
您只需要循环创建包含所有动作和图像的 HTML
import chess
import chess.pgn
from io import StringIO
board = chess.Board()
pgn_string = """
1 e4 e6 2 d4 c6 3 Nf3 Nf6 4 Bg5 h6 5 Bf4 Na6 6 Bc4 d5 7 Bd3 Nxe4 8 O-O Nb4 9 Ne5 a5
10 Qg4 f5 11 Qg6+ Ke7 12 Qf7+ Kd6 13 Nc4#
"""
pgn = StringIO(pgn_string)
game = chess.pgn.read_game(pgn)
steps = []
for number, move in enumerate(game.mainline_moves()):
text = board.san(move)
print(text)
# keep current step on list
steps.append(text)
board.push(move)
#display(board)
# create string with SVG image
svg = chess.svg.board(board)
# save string in file with name `board-0.svg`, `board-1.svg`, etc.
with open(f'board-{number}.svg', 'w') as fh:
fh.write(svg)
# --- after loop ---
#print(steps)
# create string with HTML
html = ""
for number, move in enumerate(steps):
# add move
html += f'{move}</br>\n'
# add image `board-0.svg`, `board-1.svg`, etc. (with width=300 to make it smaller)
html += f'<img src="board-{number}.svg" width="300"></br>\n'
# save html in file
with open('index.html', 'w') as fh:
fh.write(html)
web 浏览器截图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.