tableparser.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. # $Id: tableparser.py 9038 2022-03-05 23:31:46Z milde $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. This module defines table parser classes,which parse plaintext-graphic tables
  6. and produce a well-formed data structure suitable for building a CALS table.
  7. :Classes:
  8. - `GridTableParser`: Parse fully-formed tables represented with a grid.
  9. - `SimpleTableParser`: Parse simple tables, delimited by top & bottom
  10. borders.
  11. :Exception class: `TableMarkupError`
  12. :Function:
  13. `update_dict_of_lists()`: Merge two dictionaries containing list values.
  14. """
  15. __docformat__ = 'reStructuredText'
  16. import re
  17. import sys
  18. from docutils import DataError
  19. from docutils.utils import strip_combining_chars
  20. class TableMarkupError(DataError):
  21. """
  22. Raise if there is any problem with table markup.
  23. The keyword argument `offset` denotes the offset of the problem
  24. from the table's start line.
  25. """
  26. def __init__(self, *args, **kwargs):
  27. self.offset = kwargs.pop('offset', 0)
  28. DataError.__init__(self, *args)
  29. class TableParser:
  30. """
  31. Abstract superclass for the common parts of the syntax-specific parsers.
  32. """
  33. head_body_separator_pat = None
  34. """Matches the row separator between head rows and body rows."""
  35. double_width_pad_char = '\x00'
  36. """Padding character for East Asian double-width text."""
  37. def parse(self, block):
  38. """
  39. Analyze the text `block` and return a table data structure.
  40. Given a plaintext-graphic table in `block` (list of lines of text; no
  41. whitespace padding), parse the table, construct and return the data
  42. necessary to construct a CALS table or equivalent.
  43. Raise `TableMarkupError` if there is any problem with the markup.
  44. """
  45. self.setup(block)
  46. self.find_head_body_sep()
  47. self.parse_table()
  48. return self.structure_from_cells()
  49. def find_head_body_sep(self):
  50. """Look for a head/body row separator line; store the line index."""
  51. for i in range(len(self.block)):
  52. line = self.block[i]
  53. if self.head_body_separator_pat.match(line):
  54. if self.head_body_sep:
  55. raise TableMarkupError(
  56. 'Multiple head/body row separators '
  57. '(table lines %s and %s); only one allowed.'
  58. % (self.head_body_sep+1, i+1), offset=i)
  59. else:
  60. self.head_body_sep = i
  61. self.block[i] = line.replace('=', '-')
  62. if self.head_body_sep == 0 or self.head_body_sep == (len(self.block)
  63. - 1):
  64. raise TableMarkupError('The head/body row separator may not be '
  65. 'the first or last line of the table.',
  66. offset=i)
  67. class GridTableParser(TableParser):
  68. """
  69. Parse a grid table using `parse()`.
  70. Here's an example of a grid table::
  71. +------------------------+------------+----------+----------+
  72. | Header row, column 1 | Header 2 | Header 3 | Header 4 |
  73. +========================+============+==========+==========+
  74. | body row 1, column 1 | column 2 | column 3 | column 4 |
  75. +------------------------+------------+----------+----------+
  76. | body row 2 | Cells may span columns. |
  77. +------------------------+------------+---------------------+
  78. | body row 3 | Cells may | - Table cells |
  79. +------------------------+ span rows. | - contain |
  80. | body row 4 | | - body elements. |
  81. +------------------------+------------+---------------------+
  82. Intersections use '+', row separators use '-' (except for one optional
  83. head/body row separator, which uses '='), and column separators use '|'.
  84. Passing the above table to the `parse()` method will result in the
  85. following data structure::
  86. ([24, 12, 10, 10],
  87. [[(0, 0, 1, ['Header row, column 1']),
  88. (0, 0, 1, ['Header 2']),
  89. (0, 0, 1, ['Header 3']),
  90. (0, 0, 1, ['Header 4'])]],
  91. [[(0, 0, 3, ['body row 1, column 1']),
  92. (0, 0, 3, ['column 2']),
  93. (0, 0, 3, ['column 3']),
  94. (0, 0, 3, ['column 4'])],
  95. [(0, 0, 5, ['body row 2']),
  96. (0, 2, 5, ['Cells may span columns.']),
  97. None,
  98. None],
  99. [(0, 0, 7, ['body row 3']),
  100. (1, 0, 7, ['Cells may', 'span rows.', '']),
  101. (1, 1, 7, ['- Table cells', '- contain', '- body elements.']),
  102. None],
  103. [(0, 0, 9, ['body row 4']), None, None, None]])
  104. The first item is a list containing column widths (colspecs). The second
  105. item is a list of head rows, and the third is a list of body rows. Each
  106. row contains a list of cells. Each cell is either None (for a cell unused
  107. because of another cell's span), or a tuple. A cell tuple contains four
  108. items: the number of extra rows used by the cell in a vertical span
  109. (morerows); the number of extra columns used by the cell in a horizontal
  110. span (morecols); the line offset of the first line of the cell contents;
  111. and the cell contents, a list of lines of text.
  112. """
  113. head_body_separator_pat = re.compile(r'\+=[=+]+=\+ *$')
  114. def setup(self, block):
  115. self.block = block[:] # make a copy; it may be modified
  116. self.block.disconnect() # don't propagate changes to parent
  117. self.bottom = len(block) - 1
  118. self.right = len(block[0]) - 1
  119. self.head_body_sep = None
  120. self.done = [-1] * len(block[0])
  121. self.cells = []
  122. self.rowseps = {0: [0]}
  123. self.colseps = {0: [0]}
  124. def parse_table(self):
  125. """
  126. Start with a queue of upper-left corners, containing the upper-left
  127. corner of the table itself. Trace out one rectangular cell, remember
  128. it, and add its upper-right and lower-left corners to the queue of
  129. potential upper-left corners of further cells. Process the queue in
  130. top-to-bottom order, keeping track of how much of each text column has
  131. been seen.
  132. We'll end up knowing all the row and column boundaries, cell positions
  133. and their dimensions.
  134. """
  135. corners = [(0, 0)]
  136. while corners:
  137. top, left = corners.pop(0)
  138. if (top == self.bottom
  139. or left == self.right
  140. or top <= self.done[left]):
  141. continue
  142. result = self.scan_cell(top, left)
  143. if not result:
  144. continue
  145. bottom, right, rowseps, colseps = result
  146. update_dict_of_lists(self.rowseps, rowseps)
  147. update_dict_of_lists(self.colseps, colseps)
  148. self.mark_done(top, left, bottom, right)
  149. cellblock = self.block.get_2D_block(top + 1, left + 1,
  150. bottom, right)
  151. cellblock.disconnect() # lines in cell can't sync with parent
  152. cellblock.replace(self.double_width_pad_char, '')
  153. self.cells.append((top, left, bottom, right, cellblock))
  154. corners.extend([(top, right), (bottom, left)])
  155. corners.sort()
  156. if not self.check_parse_complete():
  157. raise TableMarkupError('Malformed table; parse incomplete.')
  158. def mark_done(self, top, left, bottom, right):
  159. """For keeping track of how much of each text column has been seen."""
  160. before = top - 1
  161. after = bottom - 1
  162. for col in range(left, right):
  163. assert self.done[col] == before
  164. self.done[col] = after
  165. def check_parse_complete(self):
  166. """Each text column should have been completely seen."""
  167. last = self.bottom - 1
  168. for col in range(self.right):
  169. if self.done[col] != last:
  170. return False
  171. return True
  172. def scan_cell(self, top, left):
  173. """Starting at the top-left corner, start tracing out a cell."""
  174. assert self.block[top][left] == '+'
  175. return self.scan_right(top, left)
  176. def scan_right(self, top, left):
  177. """
  178. Look for the top-right corner of the cell, and make note of all column
  179. boundaries ('+').
  180. """
  181. colseps = {}
  182. line = self.block[top]
  183. for i in range(left + 1, self.right + 1):
  184. if line[i] == '+':
  185. colseps[i] = [top]
  186. result = self.scan_down(top, left, i)
  187. if result:
  188. bottom, rowseps, newcolseps = result
  189. update_dict_of_lists(colseps, newcolseps)
  190. return bottom, i, rowseps, colseps
  191. elif line[i] != '-':
  192. return None
  193. return None
  194. def scan_down(self, top, left, right):
  195. """
  196. Look for the bottom-right corner of the cell, making note of all row
  197. boundaries.
  198. """
  199. rowseps = {}
  200. for i in range(top + 1, self.bottom + 1):
  201. if self.block[i][right] == '+':
  202. rowseps[i] = [right]
  203. result = self.scan_left(top, left, i, right)
  204. if result:
  205. newrowseps, colseps = result
  206. update_dict_of_lists(rowseps, newrowseps)
  207. return i, rowseps, colseps
  208. elif self.block[i][right] != '|':
  209. return None
  210. return None
  211. def scan_left(self, top, left, bottom, right):
  212. """
  213. Noting column boundaries, look for the bottom-left corner of the cell.
  214. It must line up with the starting point.
  215. """
  216. colseps = {}
  217. line = self.block[bottom]
  218. for i in range(right - 1, left, -1):
  219. if line[i] == '+':
  220. colseps[i] = [bottom]
  221. elif line[i] != '-':
  222. return None
  223. if line[left] != '+':
  224. return None
  225. result = self.scan_up(top, left, bottom, right)
  226. if result is not None:
  227. rowseps = result
  228. return rowseps, colseps
  229. return None
  230. def scan_up(self, top, left, bottom, right):
  231. """
  232. Noting row boundaries, see if we can return to the starting point.
  233. """
  234. rowseps = {}
  235. for i in range(bottom - 1, top, -1):
  236. if self.block[i][left] == '+':
  237. rowseps[i] = [left]
  238. elif self.block[i][left] != '|':
  239. return None
  240. return rowseps
  241. def structure_from_cells(self):
  242. """
  243. From the data collected by `scan_cell()`, convert to the final data
  244. structure.
  245. """
  246. rowseps = sorted(self.rowseps.keys()) # list of row boundaries
  247. rowindex = {}
  248. for i in range(len(rowseps)):
  249. rowindex[rowseps[i]] = i # row boundary -> row number mapping
  250. colseps = sorted(self.colseps.keys()) # list of column boundaries
  251. colindex = {}
  252. for i in range(len(colseps)):
  253. colindex[colseps[i]] = i # column boundary -> col number map
  254. colspecs = [(colseps[i] - colseps[i - 1] - 1)
  255. for i in range(1, len(colseps))] # list of column widths
  256. # prepare an empty table with the correct number of rows & columns
  257. onerow = [None for i in range(len(colseps) - 1)]
  258. rows = [onerow[:] for i in range(len(rowseps) - 1)]
  259. # keep track of # of cells remaining; should reduce to zero
  260. remaining = (len(rowseps) - 1) * (len(colseps) - 1)
  261. for top, left, bottom, right, block in self.cells:
  262. rownum = rowindex[top]
  263. colnum = colindex[left]
  264. assert rows[rownum][colnum] is None, (
  265. 'Cell (row %s, column %s) already used.'
  266. % (rownum + 1, colnum + 1))
  267. morerows = rowindex[bottom] - rownum - 1
  268. morecols = colindex[right] - colnum - 1
  269. remaining -= (morerows + 1) * (morecols + 1)
  270. # write the cell into the table
  271. rows[rownum][colnum] = (morerows, morecols, top + 1, block)
  272. assert remaining == 0, 'Unused cells remaining.'
  273. if self.head_body_sep: # separate head rows from body rows
  274. numheadrows = rowindex[self.head_body_sep]
  275. headrows = rows[:numheadrows]
  276. bodyrows = rows[numheadrows:]
  277. else:
  278. headrows = []
  279. bodyrows = rows
  280. return colspecs, headrows, bodyrows
  281. class SimpleTableParser(TableParser):
  282. """
  283. Parse a simple table using `parse()`.
  284. Here's an example of a simple table::
  285. ===== =====
  286. col 1 col 2
  287. ===== =====
  288. 1 Second column of row 1.
  289. 2 Second column of row 2.
  290. Second line of paragraph.
  291. 3 - Second column of row 3.
  292. - Second item in bullet
  293. list (row 3, column 2).
  294. 4 is a span
  295. ------------
  296. 5
  297. ===== =====
  298. Top and bottom borders use '=', column span underlines use '-', column
  299. separation is indicated with spaces.
  300. Passing the above table to the `parse()` method will result in the
  301. following data structure, whose interpretation is the same as for
  302. `GridTableParser`::
  303. ([5, 25],
  304. [[(0, 0, 1, ['col 1']),
  305. (0, 0, 1, ['col 2'])]],
  306. [[(0, 0, 3, ['1']),
  307. (0, 0, 3, ['Second column of row 1.'])],
  308. [(0, 0, 4, ['2']),
  309. (0, 0, 4, ['Second column of row 2.',
  310. 'Second line of paragraph.'])],
  311. [(0, 0, 6, ['3']),
  312. (0, 0, 6, ['- Second column of row 3.',
  313. '',
  314. '- Second item in bullet',
  315. ' list (row 3, column 2).'])],
  316. [(0, 1, 10, ['4 is a span'])],
  317. [(0, 0, 12, ['5']),
  318. (0, 0, 12, [''])]])
  319. """
  320. head_body_separator_pat = re.compile('=[ =]*$')
  321. span_pat = re.compile('-[ -]*$')
  322. def setup(self, block):
  323. self.block = block[:] # make a copy; it will be modified
  324. self.block.disconnect() # don't propagate changes to parent
  325. # Convert top & bottom borders to column span underlines:
  326. self.block[0] = self.block[0].replace('=', '-')
  327. self.block[-1] = self.block[-1].replace('=', '-')
  328. self.head_body_sep = None
  329. self.columns = []
  330. self.border_end = None
  331. self.table = []
  332. self.done = [-1] * len(block[0])
  333. self.rowseps = {0: [0]}
  334. self.colseps = {0: [0]}
  335. def parse_table(self):
  336. """
  337. First determine the column boundaries from the top border, then
  338. process rows. Each row may consist of multiple lines; accumulate
  339. lines until a row is complete. Call `self.parse_row` to finish the
  340. job.
  341. """
  342. # Top border must fully describe all table columns.
  343. self.columns = self.parse_columns(self.block[0], 0)
  344. self.border_end = self.columns[-1][1]
  345. firststart, firstend = self.columns[0]
  346. offset = 1 # skip top border
  347. start = 1
  348. text_found = None
  349. while offset < len(self.block):
  350. line = self.block[offset]
  351. if self.span_pat.match(line):
  352. # Column span underline or border; row is complete.
  353. self.parse_row(self.block[start:offset], start,
  354. (line.rstrip(), offset))
  355. start = offset + 1
  356. text_found = None
  357. elif line[firststart:firstend].strip():
  358. # First column not blank, therefore it's a new row.
  359. if text_found and offset != start:
  360. self.parse_row(self.block[start:offset], start)
  361. start = offset
  362. text_found = 1
  363. elif not text_found:
  364. start = offset + 1
  365. offset += 1
  366. def parse_columns(self, line, offset):
  367. """
  368. Given a column span underline, return a list of (begin, end) pairs.
  369. """
  370. cols = []
  371. end = 0
  372. while True:
  373. begin = line.find('-', end)
  374. end = line.find(' ', begin)
  375. if begin < 0:
  376. break
  377. if end < 0:
  378. end = len(line)
  379. cols.append((begin, end))
  380. if self.columns:
  381. if cols[-1][1] != self.border_end:
  382. raise TableMarkupError('Column span incomplete in table '
  383. 'line %s.' % (offset+1),
  384. offset=offset)
  385. # Allow for an unbounded rightmost column:
  386. cols[-1] = (cols[-1][0], self.columns[-1][1])
  387. return cols
  388. def init_row(self, colspec, offset):
  389. i = 0
  390. cells = []
  391. for start, end in colspec:
  392. morecols = 0
  393. try:
  394. assert start == self.columns[i][0]
  395. while end != self.columns[i][1]:
  396. i += 1
  397. morecols += 1
  398. except (AssertionError, IndexError):
  399. raise TableMarkupError('Column span alignment problem '
  400. 'in table line %s.' % (offset+2),
  401. offset=offset+1)
  402. cells.append([0, morecols, offset, []])
  403. i += 1
  404. return cells
  405. def parse_row(self, lines, start, spanline=None):
  406. """
  407. Given the text `lines` of a row, parse it and append to `self.table`.
  408. The row is parsed according to the current column spec (either
  409. `spanline` if provided or `self.columns`). For each column, extract
  410. text from each line, and check for text in column margins. Finally,
  411. adjust for insignificant whitespace.
  412. """
  413. if not (lines or spanline):
  414. # No new row, just blank lines.
  415. return
  416. if spanline:
  417. columns = self.parse_columns(*spanline)
  418. else:
  419. columns = self.columns[:]
  420. self.check_columns(lines, start, columns)
  421. row = self.init_row(columns, start)
  422. for i in range(len(columns)):
  423. start, end = columns[i]
  424. cellblock = lines.get_2D_block(0, start, len(lines), end)
  425. cellblock.disconnect() # lines in cell can't sync with parent
  426. cellblock.replace(self.double_width_pad_char, '')
  427. row[i][3] = cellblock
  428. self.table.append(row)
  429. def check_columns(self, lines, first_line, columns):
  430. """
  431. Check for text in column margins and text overflow in the last column.
  432. Raise TableMarkupError if anything but whitespace is in column margins.
  433. Adjust the end value for the last column if there is text overflow.
  434. """
  435. # "Infinite" value for a dummy last column's beginning, used to
  436. # check for text overflow:
  437. columns.append((sys.maxsize, None))
  438. lastcol = len(columns) - 2
  439. # combining characters do not contribute to the column width
  440. lines = [strip_combining_chars(line) for line in lines]
  441. for i in range(len(columns) - 1):
  442. start, end = columns[i]
  443. nextstart = columns[i+1][0]
  444. offset = 0
  445. for line in lines:
  446. if i == lastcol and line[end:].strip():
  447. text = line[start:].rstrip()
  448. new_end = start + len(text)
  449. main_start, main_end = self.columns[-1]
  450. columns[i] = (start, max(main_end, new_end))
  451. if new_end > main_end:
  452. self.columns[-1] = (main_start, new_end)
  453. elif line[end:nextstart].strip():
  454. raise TableMarkupError('Text in column margin in table '
  455. 'line %s.' % (first_line+offset+1),
  456. offset=first_line+offset)
  457. offset += 1
  458. columns.pop()
  459. def structure_from_cells(self):
  460. colspecs = [end - start for start, end in self.columns]
  461. first_body_row = 0
  462. if self.head_body_sep:
  463. for i in range(len(self.table)):
  464. if self.table[i][0][2] > self.head_body_sep:
  465. first_body_row = i
  466. break
  467. return (colspecs, self.table[:first_body_row],
  468. self.table[first_body_row:])
  469. def update_dict_of_lists(master, newdata):
  470. """
  471. Extend the list values of `master` with those from `newdata`.
  472. Both parameters must be dictionaries containing list values.
  473. """
  474. for key, values in newdata.items():
  475. master.setdefault(key, []).extend(values)