You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PGN/SAN获取国际象棋开局名称?求Python方案

Efficient Offline Python Solution for Chess Opening Name Lookup

To avoid hitting API rate limits, use an offline approach with the python-chess library and a standard ECO (Encyclopedia of Chess Openings) database. This method lets you parse SAN moves, compute the board state, and look up the opening name locally.

Step 1: Setup Dependencies

Install the python-chess library:

pip install python-chess

Obtain the eco.pgn file (a widely available dataset containing all standard opening lines, ECO codes, and names).

Step 2: Load the Opening Tree

Create an optimized opening tree from the eco.pgn file. This is a one-time setup—you can save the tree to avoid re-parsing the file every time.

import chess
import chess.opening
import pickle

# Load the ECO opening tree (run once)
opening_tree = chess.opening.OpeningTree.from_pgn_file("eco.pgn")

# Save the tree to a file for future use
with open("opening_tree.pkl", "wb") as f:
    pickle.dump(opening_tree, f)

# Later, load the saved tree instead of re-parsing eco.pgn
# with open("opening_tree.pkl", "rb") as f:
#     opening_tree = pickle.load(f)

Step 3: Parse SAN Moves and Look Up Opening

Convert your SAN moves to a board state, then find the matching opening. If an exact match isn't found, backtrack to the deepest valid opening variation.

def get_opening_name(san_moves, opening_tree):
    board = chess.Board()
    # Play through each SAN move
    for move in san_moves.split():
        try:
            board.push_san(move)
        except ValueError:
            return "Invalid SAN move"
    
    # Find exact opening match
    opening = opening_tree.find(board)
    if opening:
        return opening.name
    
    # Backtrack to find the closest valid opening
    current_board = board.copy()
    while current_board.move_stack:
        current_board.pop()
        opening = opening_tree.find(current_board)
        if opening:
            return f"Closest opening: {opening.name}"
    
    return "No opening found"

# Example usage
san_moves = "e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 g6"
print(get_opening_name(san_moves, opening_tree))
# Output: Sicilian Defense: Dragon Variation

Key Notes

  • Offline Efficiency: No API calls mean no rate limits, and lookups are fast after the initial tree setup.
  • Coverage: The eco.pgn file includes all standard openings and their main variations. For newer or niche openings, you may need a more comprehensive opening database, but ECO covers most common use cases.
  • Error Handling: The code includes basic validation for invalid SAN moves—adjust this based on your input quality.

内容的提问来源于stack exchange,提问作者hpy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:39:47