如何通过PGN/SAN获取国际象棋开局名称?求Python方案
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.pgnfile 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

