Wolfram Research

Function Repository Resource:

ImportPGN

Source Notebook

Import a PGN file or string as an association of structured chess data

Contributed by: Paco Jain (Wolfram Research)

ResourceFunction["ImportPGN"]["input"]

imports Portable Game Notation (PGN) from a file or string and outputs a list of associations of structured chess data.

Details and Options

If FileExistsQ["input"] is True, then ResourceFunction["ImportPGN"]["input"] attempts to read plaintext PGN input from the corresponding file; otherwise, it interprets "input" directly as PGN.
The keys of the output of ResourceFunction["ImportPGN"] are "GameNumber", "Event", "Site", "Date", "Round", "White", "Black", "Result", "ECO", "PlyCount", "MoveList" and "MoveListString".
If "input" does not contain any properly formatted PGN games, ResourceFunction["ImportPGN"]["input"] returns {}.

Examples

Basic Examples

Start with a PGN text string:

Import this string as structured chess game data:

In[1]:=
ResourceFunction["ImportPGN"][myPGNString]
Out[1]=

Write the previous PGN out to a file:

In[2]:=
pgnFilename = CreateFile[]
Out[2]=
In[3]:=
WriteString[pgnFilename, myPGNString]

Import structured chess data directly from the created file:

In[4]:=
ResourceFunction["ImportPGN"][pgnFilename]
Out[4]=

Properties and Relations

If "input" does not contain any properly formatted PGN games, ImportPGN["input"] returns {}:

In[5]:=
ResourceFunction["ImportPGN"]["blah"]
Out[5]=

The concatenation of one or more PGN game strings yields a list of game data associations, which are each assigned consecutive integer "GameNumber" keys:

In[6]:=
mySecondPGN = "[Site \"Champaign, IL\"]\n[Date \"2019.3.20\"]\n[White \"Player \
1\"]\n[Black \"Player 2\"]\n[Result \"1/2-1/2\"]\n[ECO \"C48f\"]\n\
[PlyCount \"14\"]\n\n1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bc5 5. O-O \
d6 6. d4 exd4 7. Nxd4 Bxd4 1/2-1/2";
ResourceFunction["ImportPGN"][
  StringRiffle[{myPGNString, mySecondPGN}, "\n\n"]];
SelectFirst[%, ("GameNumber" /. #) == 2 &]
Out[7]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

See Also

License Information