Parse a string previously printed as a `Table` back into a `Table`.
(string)
| 361 | |
| 362 | @staticmethod |
| 363 | def parse(string): |
| 364 | """ |
| 365 | Parse a string previously printed as a `Table` back into a `Table`. |
| 366 | """ |
| 367 | lines = string.split("\n") |
| 368 | |
| 369 | # Find the location and contents of column headers in the string. |
| 370 | # Assume only single spaces between words in column headers. |
| 371 | matches = re.finditer(r"([\w\d]+\s?[\w\d]+)+", lines[0]) |
| 372 | columns = [(m.start(), m.group()) for m in matches] |
| 373 | |
| 374 | # Build a table from the column header contents. |
| 375 | table = Table([c[1] for c in columns]) |
| 376 | |
| 377 | # Fill in the subsequent rows. |
| 378 | for line in lines[1:]: |
| 379 | row = [] |
| 380 | start_indices = [c[0] for c in columns] |
| 381 | |
| 382 | for i, start_index in enumerate(start_indices): |
| 383 | if i + 1 < len(start_indices): |
| 384 | column = line[start_index:start_indices[i + 1]] |
| 385 | else: |
| 386 | column = line[start_index:] |
| 387 | |
| 388 | row.append(str(column.strip())) |
| 389 | |
| 390 | table.add_row(row) |
| 391 | |
| 392 | return table |