Answers.Body: <p>First, worth noting that this question has nothing to do with chess. It is a programming question and a simple one at that.</p>
  <p>The answer is very simple. Write a program to read the files and parse them. The pseudo-code looks something like this:</p>
  <p>Read the file<br />
  For each line</p>
  <ol>
  <li>find and extract any keywords like &quot;WhiteELO&quot;, &quot;UTCDate&quot;, etc.</li>
  <li>If there is no keyword then throw the line away (or do something else if you need to)</li>
  <li>If there is a keyword then extract and store the associated data</li>
  </ol>
  <p>Once you have processed all the lines of the game in the pgn then write a formatted line to your output file.</p>
  <p>Note that for spreadsheet-readable files you can use something like &quot;;&quot; (semicolon) as the field delimiter. Probably better than &quot;,&quot; (comma) since the title and player name fields are likely to contain commas.</p>
  <p>Note that there was nothing whatsoever to do with chess in that answer. It was all simple data processing.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2021-05-01T11:50:42.890Z
Answers.LastActivityDate: 2021-05-01T11:50:42.890Z
Answers.UserDisplayName: Brian Towers
Answers.Body: <p>Update 2: Fixed now. see the 'json' vs the 'preformed'. WOW.</p>
  <p>Update 1: It appears Mike Steelson has an answer <a href="https://stackoverflow.com/questions/67345784/how-do-convert-parse-extract-data-from-a-pgn-into-a-spreadsheet-google-sheet-exc">here</a>, where the code is given as</p>
  <pre><code>=arrayformula( regexextract(split( substitute(substitute(substitute(getDataJSON(A1;&quot;/games&quot;;&quot;/pgn&quot;);&quot;[&quot;;&quot;&quot;);&quot;]&quot;;&quot;&quot;);&quot;&quot;&quot;&quot;;&quot;&quot;) ;char(10));&quot;\s.*&quot;) )
  </code></pre>
  <p>with an example given here</p>
  <p><a href="https://docs.google.com/spreadsheets/d/1MX1o5qdy0K3gTMzbimUV3SmFf-0XPCSJ8Vz4IjI-8Ak/copy" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1MX1o5qdy0K3gTMzbimUV3SmFf-0XPCSJ8Vz4IjI-8Ak/copy</a></p>
  <p>It appears there's a problem when it gets to the case of chess960 only. Consider for example <a href="https://www.chess.com/member/dukov5" rel="nofollow noreferrer">this player</a>: Replacing 'gmwso' with the player's username will yield a weird output. i imagine the output will be messier for mixed chess960 and chess.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2021-05-02T09:10:54.647Z
Answers.LastActivityDate: 2021-05-02T09:10:54.647Z
Answers.UserDisplayName: BCLC
Answers.Body: <p>I avoided having to write a programming script to convert a PGN games file into a spreadsheet, but I used a word processing application instead.</p>
  <p>The WP app needs to support regular expressions (regex), which allow you to use variables as well as the usual literals. Basically, this is activated by setting a checkbox in the Find/Replace dialog(s), but you need to use special characters to specify how you want the text manipulated. (The helpfile on &quot;regex&quot; explains how, with examples.)</p>
  <p>The key is that each variable in a PGN game header stands on its own line. To concatenate them all for use by a spreadsheet, you need to convert the paragraph separator characters, which I'll call [Para] characters, into [Tab] characters.</p>
  <p>But first, knowing that all PGN games are separated by a blank line indicates there are two para characters separating them. This makes the [Para] chars ambiguous, except for the pairing characteristic when they're used for game separation. You want the games on separate rows in your spreadsheet, so you need to preserve this game separation info and restore it once the concatenation is complete.</p>
  <p>So, first I copied (or opened) the PGN file in(to) MS Word.</p>
  <p>Then I regex-replaced all the double-para characters with a special-character pair I reserved for that purpose: &quot;&amp;&amp;&quot;. That's the delimiter between games.</p>
  <p>(Note: As you manipulate the file in Word, it will immediately start looking weird. Ignore that, and just execute the steps.)</p>
  <p>Next, I regex-replaced all the &quot;][Para]&quot; End-of-PGN-Field character pairs with a special-character pair I reserved for that purpose: &quot;]%&quot;. The &quot;]&quot; is just a target-finder; it specifies that only the lines ending in a &quot;]&quot; are to be concatenated. The &quot;%&quot; becomes the delimiter between the PGN fields, and between the last field and the start of the game score.</p>
  <p>Next, you have to concatenate the moves, which have been arbitrarily split by the PGN file creation software so that they're human-readable using a simple text processor, like Notepad.</p>
  <p>To do this, I regex-replaced all remaining [Para] chars with space &quot; &quot; chars. This concatenates the game scores, with at least one space between the end of one line and the beginning of the next from the PGN file. Note that this has no effect on the PGN header fields or the game separations; those were already converted to special characters to prevent them from being affected by this step.</p>
  <p>Next I regex-replaced the &quot;%&quot; characters with &quot;[Tab]&quot; characters so the PGN fields will load into separate columns in the spreadsheet when the time comes.</p>
  <p>Finally, I regex-replaced the &quot;&amp;&amp;&quot; character pairs with [Para] chars so that each game would be on its own row in the spreadsheet.</p>
  <p>Finally, I selected all (you can use &quot;Select-All&quot;, instead of trying to drag-select over sometimes 100's of pages, but even that can be done by placing the cursor at the start of the text [Ctrl]-[End]) of the text from the document, opened a fresh spreadsheet, and pasted the text.</p>
  <p>A few caveats:</p>
  <ol>
  <li>If you find that some of the PGN games have one set of PGN header fields, and some of them have a different set (this shouldn't happen, but might if your PGN file creator adds uncommon fields only for the games that came with that data, and omits them for others), then you can easily detect the disparities by just looking for misalignments in one of the last PGN file columns in the spreadsheet. If this affects only a small number of rows, you can generally correct it with some manual copy-pasta work in the spreadsheet to realign the fields. I always dropped any PGN field that only a few games had.</li>
  </ol>
  <p>Before you undertake the manual process, assess the magnitude of the effort. How many rows are non-conforming to the standard content of the majority of the games? If it's a lot, and you don't need the unusual fields, it may be more efficient to just repeat the text file conversion process, but precede it by first removing all of these non-conforming fields and their data. Again, you can use a regex-replace to specify a starting &quot;[&quot;, the name of the field plus a [wildcard] character to specify all of the non-essential text, as well as a &quot;]&quot;, and then just replace them all with nothing.</p>
  <p>Some may observe that if we had known this would be a problem before beginning the first conversion cycle, we could have saved that effort. That's true, but it turns out the most reliable way to find the anomalies is to produce a pilot version of the spreadsheet, and look for the misalignments of PGN fields caused by the interjection of the unusual fields' data in the anomalous rows. This is comprehensive, 100% effective at avoiding false positives and false negatives, and fairly easy. In the conversion process itself, once a step has been executed and verified to operate correctly, can be easily repeated using shortcuts like &quot;Last Used&quot; dropdown box selections in the Regex dialog box, or even automated with simple macros or one master macro (though in that case we're back to programming).</p>
  <ol start="2">
  <li>Sometimes there are anomalies in PGN game files that cause a game (or even swathes of them) not to be recognized by a chess reader. (I'll leave to you whether it's worth pursuing and addressing how they occurred.) Therefore, you should always get a count of the PGN games that are <em>supposed</em> to be in the file by counting the number of occurrences of a telltale, standard PGN field (I like to use the &quot;White&quot; field). To get the count, load (a copy of) the PGN file into your word processor and do a replace of &quot;White&quot; with &quot;White&quot;. The file will be identical, but the word processor will report the number of replacements.</li>
  </ol>
  <p>Then load the file into a chess reader, and check the number of games it reports in the file. If the numbers don't match (the reader's count cannot be higher, but it can be lower), I always isolate the games that the chess reader can't read and try to recover them. Most of the time, it's just a matter of correcting some character anomaly, a missing field delimiter &quot;[&quot; or &quot;]&quot;, or (rarely) a missing required PGN field.</p>
  <p>If this problem exists, it may cause the reader to stumble and be unable to read several perfectly intact games after the offending game; don't assume that subsequent &quot;unreadable&quot; games all have problems. Often, fixing the first in the set and then trying again magically makes all of them readable.</p>
  <ol start="3">
  <li>PGN readers are (by the specification in the standard) very tolerant of lots of sloppiness, so they ignore most disparities between one game and the next, including the order of fields. If you get all of the PGN games in a file from one source, then such disparities shouldn't appear at all. But if you concatenate games from different sources (which I highly discourage, for this reason), they are likely to show up. Then, trying to get the data from multiple sources to align in the right spreadsheet columns for all of the rows can be a real exercise.</li>
  </ol>
  <p>Better to load PGN files from different sources into separate spreadsheet tabs, and then merge them later after any column inconsistencies between them have been identified and sorted out.</p>
  <p>Why do this analysis prep work at all?
  I've used it to find games that met several criteria:</p>
  <ul>
  <li>Upsets, based on the underdog's ELO deficit vs their opponent</li>
  <li>Miniatures (games with decisive results in under [game-length-limit] moves.)</li>
  </ul>
  <p>but the ability to sort, filter and calculate based on the PGN fields alone has made it worthwhile in my research.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-07-05T19:14:43.937Z
Answers.Text: Note that very long game scores, say, above 110 moves, can't be contained in a single spreadsheet cell. Depending on your software, the remaining moves might get truncated or they may end up in the next cell on the row. In dealing with files containing fewer than 20k games, these were rare enough for me to just analyze them manually. Since the spreadsheet cell char limit is a hard stop, you just have to work around it (or switch spreadsheet apps).
Answers.UserDisplayName: jaxter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-07-05T19:09:13.167Z
Answers.LastActivityDate: 2023-07-05T19:09:13.167Z
Answers.UserDisplayName: jaxter
Body: <p>Sequel to this question: <a href="https://chess.stackexchange.com/questions/34842/live-statistics-chess960-from-chess-com">Live statistics chess960 from chess.com?</a></p>
  <p>So suppose I go to like</p>
  <p><a href="https://api.chess.com/pub/player/gmwso/games/2020/12" rel="nofollow noreferrer">https://api.chess.com/pub/player/gmwso/games/2020/12</a></p>
  <p>or</p>
  <p><a href="https://api.chess.com/pub/player/gmwso/games/2020/12/pgn" rel="nofollow noreferrer">https://api.chess.com/pub/player/gmwso/games/2020/12/pgn</a></p>
  <p>there's gonna be a bunch of stuff like say</p>
  <pre><code>[UTCDate &quot;2018.01.03&quot;]
  [WhiteElo &quot;2706&quot;]
  [BlackElo &quot;2940&quot;]
  </code></pre>
  <p>How do I get this data into a spreadsheet like column 1 is all the dates, column 2 is the corresponding white elo, column 3 black elo, col4 white username and col5 black username?</p>
  <hr />
  <p>Update 2: Fixed now. see the 'json' vs the 'preformed'. WOW.</p>
  <p>Update 1: It appears Mike Steelson has an answer <a href="https://stackoverflow.com/questions/67345784/how-do-convert-parse-extract-data-from-a-pgn-into-a-spreadsheet-google-sheet-exc">here</a>, where the code is given as</p>
  <pre><code>=arrayformula( regexextract(split( substitute(substitute(substitute(getDataJSON(A1;&quot;/games&quot;;&quot;/pgn&quot;);&quot;[&quot;;&quot;&quot;);&quot;]&quot;;&quot;&quot;);&quot;&quot;&quot;&quot;;&quot;&quot;) ;char(10));&quot;\s.*&quot;) )
  </code></pre>
  <p>with an example given here</p>
  <p><a href="https://docs.google.com/spreadsheets/d/1MX1o5qdy0K3gTMzbimUV3SmFf-0XPCSJ8Vz4IjI-8Ak/copy" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1MX1o5qdy0K3gTMzbimUV3SmFf-0XPCSJ8Vz4IjI-8Ak/copy</a></p>
  <p>It appears there's a problem when it gets to the case of chess960 only. Consider for example <a href="https://www.chess.com/member/dukov5" rel="nofollow noreferrer">this player</a>: Replacing 'gmwso' with the player's username will yield a weird output. i imagine the output will be messier for mixed chess960 and chess.</p>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2022-11-20T05:54:28.720Z
Comments.Text: Cross-posted: https://stackoverflow.com/q/67345784/781723, https://chess.stackexchange.com/q/34943/12996.  Please [do not post the same question on multiple sites](https://meta.stackexchange.com/q/64068).
Comments.UserDisplayName: D.W.
Tags: <chess-variants><programming><database><statistics><chess960>
Title: How do convert/parse/extract data from a PGN into a spreadsheet/google sheet/excel file?
ThreadText: # How do convert/parse/extract data from a PGN into a spreadsheet/google sheet/excel file?
  
  (Asked by: username_0 on 2021-05-01)
  
  Sequel to this question: [Live statistics chess960 from chess.com?](https://chess.stackexchange.com/questions/34842/live-statistics-chess960-from-chess-com)
  
  So suppose I go to like
  
  <https://api.chess.com/pub/player/gmwso/games/2020/12>
  
  or
  
  <https://api.chess.com/pub/player/gmwso/games/2020/12/pgn>
  
  there's gonna be a bunch of stuff like say
  
  ```
  [UTCDate "2018.01.03"]
  [WhiteElo "2706"]
  [BlackElo "2940"]
  
  ```
  
  How do I get this data into a spreadsheet like column 1 is all the dates, column 2 is the corresponding white elo, column 3 black elo, col4 white username and col5 black username?
  
  ---
  
  Update 2: Fixed now. see the 'json' vs the 'preformed'. WOW.
  
  Update 1: It appears Mike Steelson has an answer [here](https://stackoverflow.com/questions/67345784/how-do-convert-parse-extract-data-from-a-pgn-into-a-spreadsheet-google-sheet-exc), where the code is given as
  
  ```
  =arrayformula( regexextract(split( substitute(substitute(substitute(getDataJSON(A1;"/games";"/pgn");"[";"");"]";"");"""";"") ;char(10));"\s.*") )
  
  ```
  
  with an example given here
  
  <https://docs.google.com/spreadsheets/d/1MX1o5qdy0K3gTMzbimUV3SmFf-0XPCSJ8Vz4IjI-8Ak/copy>
  
  It appears there's a problem when it gets to the case of chess960 only. Consider for example [this player](https://www.chess.com/member/dukov5): Replacing 'gmwso' with the player's username will yield a weird output. i imagine the output will be messier for mixed chess960 and chess.
  
  **Tags:** chess-variants, programming, database, statistics, chess960
  
  > **Comments:**
  > **username_1**: Cross-posted: https://stackoverflow.com/q/67345784/781723, https://chess.stackexchange.com/q/34943/12996.  Please [do not post the same question on multiple sites](https://meta.stackexchange.com/q/64068).  
  
  ---
  
  ## 3 answers
  
  ### Answer by username_2 on 2021-05-01. Score: 2
  
  First, worth noting that this question has nothing to do with chess. It is a programming question and a simple one at that.
  
  The answer is very simple. Write a program to read the files and parse them. The pseudo-code looks something like this:
  
  Read the file  
  For each line
  
  1. find and extract any keywords like "WhiteELO", "UTCDate", etc.
  2. If there is no keyword then throw the line away (or do something else if you need to)
  3. If there is a keyword then extract and store the associated data
  
  Once you have processed all the lines of the game in the pgn then write a formatted line to your output file.
  
  Note that for spreadsheet-readable files you can use something like ";" (semicolon) as the field delimiter. Probably better than "," (comma) since the title and player name fields are likely to contain commas.
  
  Note that there was nothing whatsoever to do with chess in that answer. It was all simple data processing.
  
  
  ---
  
  ### Answer by username_0 on 2021-05-02. Score: 1
  
  Update 2: Fixed now. see the 'json' vs the 'preformed'. WOW.
  
  Update 1: It appears Mike Steelson has an answer [here](https://stackoverflow.com/questions/67345784/how-do-convert-parse-extract-data-from-a-pgn-into-a-spreadsheet-google-sheet-exc), where the code is given as
  
  ```
  =arrayformula( regexextract(split( substitute(substitute(substitute(getDataJSON(A1;"/games";"/pgn");"[";"");"]";"");"""";"") ;char(10));"\s.*") )
  
  ```
  
  with an example given here
  
  <https://docs.google.com/spreadsheets/d/1MX1o5qdy0K3gTMzbimUV3SmFf-0XPCSJ8Vz4IjI-8Ak/copy>
  
  It appears there's a problem when it gets to the case of chess960 only. Consider for example [this player](https://www.chess.com/member/dukov5): Replacing 'gmwso' with the player's username will yield a weird output. i imagine the output will be messier for mixed chess960 and chess.
  
  
  ---
  
  ### Answer by username_3 on 2023-07-05. Score: 0
  
  I avoided having to write a programming script to convert a PGN games file into a spreadsheet, but I used a word processing application instead.
  
  The WP app needs to support regular expressions (regex), which allow you to use variables as well as the usual literals. Basically, this is activated by setting a checkbox in the Find/Replace dialog(s), but you need to use special characters to specify how you want the text manipulated. (The helpfile on "regex" explains how, with examples.)
  
  The key is that each variable in a PGN game header stands on its own line. To concatenate them all for use by a spreadsheet, you need to convert the paragraph separator characters, which I'll call [Para] characters, into [Tab] characters.
  
  But first, knowing that all PGN games are separated by a blank line indicates there are two para characters separating them. This makes the [Para] chars ambiguous, except for the pairing characteristic when they're used for game separation. You want the games on separate rows in your spreadsheet, so you need to preserve this game separation info and restore it once the concatenation is complete.
  
  So, first I copied (or opened) the PGN file in(to) MS Word.
  
  Then I regex-replaced all the double-para characters with a special-character pair I reserved for that purpose: "&&". That's the delimiter between games.
  
  (Note: As you manipulate the file in Word, it will immediately start looking weird. Ignore that, and just execute the steps.)
  
  Next, I regex-replaced all the "][Para]" End-of-PGN-Field character pairs with a special-character pair I reserved for that purpose: "]%". The "]" is just a target-finder; it specifies that only the lines ending in a "]" are to be concatenated. The "%" becomes the delimiter between the PGN fields, and between the last field and the start of the game score.
  
  Next, you have to concatenate the moves, which have been arbitrarily split by the PGN file creation software so that they're human-readable using a simple text processor, like Notepad.
  
  To do this, I regex-replaced all remaining [Para] chars with space " " chars. This concatenates the game scores, with at least one space between the end of one line and the beginning of the next from the PGN file. Note that this has no effect on the PGN header fields or the game separations; those were already converted to special characters to prevent them from being affected by this step.
  
  Next I regex-replaced the "%" characters with "[Tab]" characters so the PGN fields will load into separate columns in the spreadsheet when the time comes.
  
  Finally, I regex-replaced the "&&" character pairs with [Para] chars so that each game would be on its own row in the spreadsheet.
  
  Finally, I selected all (you can use "Select-All", instead of trying to drag-select over sometimes 100's of pages, but even that can be done by placing the cursor at the start of the text [Ctrl]-[End]) of the text from the document, opened a fresh spreadsheet, and pasted the text.
  
  A few caveats:
  
  1. If you find that some of the PGN games have one set of PGN header fields, and some of them have a different set (this shouldn't happen, but might if your PGN file creator adds uncommon fields only for the games that came with that data, and omits them for others), then you can easily detect the disparities by just looking for misalignments in one of the last PGN file columns in the spreadsheet. If this affects only a small number of rows, you can generally correct it with some manual copy-pasta work in the spreadsheet to realign the fields. I always dropped any PGN field that only a few games had.
  
  Before you undertake the manual process, assess the magnitude of the effort. How many rows are non-conforming to the standard content of the majority of the games? If it's a lot, and you don't need the unusual fields, it may be more efficient to just repeat the text file conversion process, but precede it by first removing all of these non-conforming fields and their data. Again, you can use a regex-replace to specify a starting "[", the name of the field plus a [wildcard] character to specify all of the non-essential text, as well as a "]", and then just replace them all with nothing.
  
  Some may observe that if we had known this would be a problem before beginning the first conversion cycle, we could have saved that effort. That's true, but it turns out the most reliable way to find the anomalies is to produce a pilot version of the spreadsheet, and look for the misalignments of PGN fields caused by the interjection of the unusual fields' data in the anomalous rows. This is comprehensive, 100% effective at avoiding false positives and false negatives, and fairly easy. In the conversion process itself, once a step has been executed and verified to operate correctly, can be easily repeated using shortcuts like "Last Used" dropdown box selections in the Regex dialog box, or even automated with simple macros or one master macro (though in that case we're back to programming).
  
  2. Sometimes there are anomalies in PGN game files that cause a game (or even swathes of them) not to be recognized by a chess reader. (I'll leave to you whether it's worth pursuing and addressing how they occurred.) Therefore, you should always get a count of the PGN games that are *supposed* to be in the file by counting the number of occurrences of a telltale, standard PGN field (I like to use the "White" field). To get the count, load (a copy of) the PGN file into your word processor and do a replace of "White" with "White". The file will be identical, but the word processor will report the number of replacements.
  
  Then load the file into a chess reader, and check the number of games it reports in the file. If the numbers don't match (the reader's count cannot be higher, but it can be lower), I always isolate the games that the chess reader can't read and try to recover them. Most of the time, it's just a matter of correcting some character anomaly, a missing field delimiter "[" or "]", or (rarely) a missing required PGN field.
  
  If this problem exists, it may cause the reader to stumble and be unable to read several perfectly intact games after the offending game; don't assume that subsequent "unreadable" games all have problems. Often, fixing the first in the set and then trying again magically makes all of them readable.
  
  3. PGN readers are (by the specification in the standard) very tolerant of lots of sloppiness, so they ignore most disparities between one game and the next, including the order of fields. If you get all of the PGN games in a file from one source, then such disparities shouldn't appear at all. But if you concatenate games from different sources (which I highly discourage, for this reason), they are likely to show up. Then, trying to get the data from multiple sources to align in the right spreadsheet columns for all of the rows can be a real exercise.
  
  Better to load PGN files from different sources into separate spreadsheet tabs, and then merge them later after any column inconsistencies between them have been identified and sorted out.
  
  Why do this analysis prep work at all?
  I've used it to find games that met several criteria:
  
  * Upsets, based on the underdog's ELO deficit vs their opponent
  * Miniatures (games with decisive results in under [game-length-limit] moves.)
  
  but the ability to sort, filter and calculate based on the PGN fields alone has made it worthwhile in my research.
  
  > **Comments:**
  > **username_3**: Note that very long game scores, say, above 110 moves, can't be contained in a single spreadsheet cell. Depending on your software, the remaining moves might get truncated or they may end up in the next cell on the row. In dealing with files containing fewer than 20k games, these were rare enough for me to just analyze them manually. Since the spreadsheet cell char limit is a hard stop, you just have to work around it (or switch spreadsheet apps).  
  
  ---
  
  