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 (4) 

Start with a PGN text string:

In[1]:=
myPGNString = "[Event \"DSB-07.Kongress\"]\n[Site \"Dresden\"]\n[Date \"1892.??.??\"]\n[Round \"16\"]\n[White \"Paulsen, Wilfried\"]\n[Black \"Von Gottschall, Hermann\"]\n[Result \"0-1\"]\n[ECO \"A00d\"]\n[PlyCount \"64\"]\n1. h3 e5 2. c4 Nc6 3. e3 Nf6 4. a3 d5 5. cxd5 Nxd5 6. Qc2 a6 7. Nf3 Be6\n8. Nc3 Be7 9. Ne4 O-O 10. Nc5 Bxc5 11. Qxc5 Qd7 12. b4 f6 13. Bb2 Rad8\n14. Rc1 Qf7 15. Qc2 Kh8 16. g4 Rfe8 17. b5 axb5 18. Bxb5 Rd6 19. Kf1 Nb6\n20. d3 Red8 21. d4 exd4 22. Bxd4 Bd5 23. e4 Bb3 24. Qc3 Nxd4 25. Nxd4 Rxd4\n26. Qxc7 Qxc7 27. Rxc7 Rxe4 28. Rxb7 Nc4 29. Kg2 Ne5 30. Bc6 Bc2\n31. Rc1 Rc4 32. Re1 Rxc6 0-1";

Import this string as structured chess game data:

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

Write the previous PGN out to a file:

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

Import structured chess data directly from the created file:

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

Properties and Relations (2) 

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

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

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[7]:=
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

Related Resources

License Information