Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

ascii_table.py 10 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
  1. import re
  2. from typing import Union, List
  3. _opts_halign = {'l':0,'c':1,'r':2}
  4. _opts_valign = {'t':0,'m':1,'b':2}
  5. """
  6. test = [
  7. '|c99 TABLE NAME',
  8. '|3 3-span left align\n multiline row |rb2 2-span right bottom align',
  9. '|c WWWWWWWWWW |c WWWWWWWWWW |c WWWWWWWWWW |c WWWWWWWWWW |c WWWWWWWWWW',
  10. '|c3 center aligned 3-span |r2 2-span right align',
  11. '|r 0 |c3 Center align\nmulti\nline\nrow |l 1.00',
  12. '|r 1 |r3 Right align\nmulti\nline\nrow |l 1.00',
  13. '| ? | s',
  14. '| ? | Three |c Two | asdasd | asdasd',
  15. '| ? |3 asdasdasdasdasdasdasdasdasdasdasda |3 asdasd',
  16. ]
  17. """
  18. class Column:
  19. __slots__ = ['halign', 'valign', 'span', 'content']
  20. def __init__(self, halign : int = 0, valign : int = 0, span : int = 1, content : str = None):
  21. self.halign, self.valign, self.span, self.content = halign, valign, span, content
  22. def __str__(self): return f'{self.content} s:{self.span}'
  23. def __repr__(self): return self.__str__()
  24. def split(self, sep : Union[str,int], maxsplit=-1) -> List['Column']:
  25. result = []
  26. if isinstance(sep, int):
  27. c_split = [ self.content[:sep], self.content[sep:] ]
  28. else:
  29. c_split = self.content.split(sep, maxsplit=maxsplit)
  30. if len(c_split) == 1:
  31. return [self]
  32. for c in c_split:
  33. col = Column()
  34. col.halign = self.halign
  35. col.valign = self.valign
  36. col.span = self.span
  37. col.content = c
  38. result.append(col)
  39. return result
  40. def copy(self, content=...):
  41. if content is Ellipsis:
  42. content=self.content
  43. column = Column()
  44. column.halign = self.halign
  45. column.valign = self.valign
  46. column.span = self.span
  47. column.content = content
  48. return column
  49. def ascii_table(table_def : List[str],
  50. min_table_width : int = None,
  51. max_table_width : int = None,
  52. fixed_table_width : int = None,
  53. style_borderless = False,
  54. left_border : str= '|',
  55. right_border : str = '|',
  56. border : str= '|',
  57. row_symbol : str = '-',
  58. col_def_delim = '|',
  59. ) -> str:
  60. """
  61. arguments
  62. table_def list of str
  63. |[options] data - defines new column
  64. options:
  65. halign: l - left (default), c - center, r - right
  66. valign: t - top (default), m - center, b - bottom
  67. 1..N - col span
  68. example: ['|c99 TABLE NAME',
  69. '|l first col |r second col']
  70. """
  71. if style_borderless:
  72. left_border, right_border, border, row_symbol = None, None, ' | ', None
  73. if fixed_table_width is not None:
  74. min_table_width = fixed_table_width
  75. max_table_width = fixed_table_width
  76. if min_table_width is not None and max_table_width is not None:
  77. if min_table_width > max_table_width:
  78. raise ValueError('min_table_width > max_table_width')
  79. col_spacing = len(border) if border is not None else 0
  80. cols_count = 0
  81. # Parse columns in table_def
  82. rows : List[List[Column]] = []
  83. for raw_line in table_def:
  84. # Line must starts with column definition
  85. if len(raw_line) == 0 or raw_line[0] != col_def_delim:
  86. raise ValueError(f'Line does not start with | symbol, content: "{raw_line}"')
  87. # Parsing raw columns
  88. row : List[Column] = []
  89. i_raw_col = 0
  90. raw_line_split = raw_line.split(col_def_delim)[1:]
  91. raw_line_split_len = len(raw_line_split)
  92. for n_raw_col, raw_col in enumerate(raw_line_split):
  93. # split column options and content
  94. col_opts, col_content = ( raw_col.split(' ', maxsplit=1) + [''] )[:2]
  95. # Parse column options
  96. col = Column(content=col_content)
  97. for col_opt in re.findall('[lcr]|[tmb]|[0-9]+', col_opts.lower()):
  98. h = _opts_halign.get(col_opt, None)
  99. if h is not None:
  100. col.halign = h
  101. continue
  102. v = _opts_valign.get(col_opt, None)
  103. if v is not None:
  104. col.valign = v
  105. continue
  106. col.span = max(1, int(col_opt))
  107. row.append(col)
  108. if n_raw_col != raw_line_split_len-1:
  109. i_raw_col += col.span
  110. else:
  111. # total max columns, by last column without span
  112. cols_count = max(cols_count, i_raw_col+1)
  113. rows.append(row)
  114. # Cut span of last cols to fit cols_count
  115. for row in rows:
  116. row[-1].span = cols_count - (sum(col.span for col in row) - row[-1].span)
  117. # Compute cols border indexes
  118. cols_border = [0]*cols_count
  119. for i_col_max in range(cols_count+1):
  120. for row in rows:
  121. i_col = 0
  122. col_border = 0
  123. for col in row:
  124. i_col += col.span
  125. col_max_len = max([ len(x.strip()) for x in col.content.split('\n')])
  126. col_border = cols_border[i_col-1] = max(cols_border[i_col-1], col_border + col_max_len)
  127. if i_col >= i_col_max:
  128. break
  129. col_border += col_spacing
  130. # fix zero cols border
  131. for i_col, col_border in enumerate(cols_border):
  132. if i_col != 0 and col_border == 0:
  133. cols_border[i_col] = cols_border[i_col-1]
  134. table_width = cols_border[-1] + (len(left_border) if left_border is not None else 0) + \
  135. (len(right_border) if right_border is not None else 0)
  136. # Determine size of table width
  137. table_width_diff = 0
  138. if max_table_width is not None:
  139. table_width_diff = max(table_width_diff, table_width - max_table_width)
  140. if min_table_width is not None:
  141. table_width_diff = min(table_width_diff, table_width - min_table_width)
  142. if table_width_diff != 0:
  143. # >0 :shrink, <0 :expand table
  144. diffs = [ x-y for x,y in zip(cols_border, [0]+cols_border[:-1] ) ]
  145. while table_width_diff != 0:
  146. if table_width_diff > 0:
  147. max_diff = max(diffs)
  148. if max_diff <= col_spacing:
  149. raise Exception('Unable to shrink the table to fit max_table_width.')
  150. diffs[ diffs.index(max_diff) ] -= 1
  151. else:
  152. diffs[ diffs.index(min(diffs)) ] += 1
  153. table_width_diff += 1 if table_width_diff < 0 else -1
  154. for i in range(len(cols_border)):
  155. cols_border[i] = diffs[i] if i == 0 else cols_border[i-1] + diffs[i]
  156. # recompute new table_width
  157. table_width = cols_border[-1] + (len(left_border) if left_border is not None else 0) + \
  158. (len(right_border) if right_border is not None else 0)
  159. # Process columns for \n and col width
  160. new_rows : List[List[List[Column]]] = []
  161. for row in rows:
  162. row_len = len(row)
  163. # Gather multi rows for every col
  164. cols_sub_rows = []
  165. i_col = 0
  166. col_border = 0
  167. for col in row:
  168. i_col += col.span
  169. col_border_next = cols_border[i_col-1]
  170. col_width = col_border_next-col_border
  171. # slice col to sub rows by \n separator and col_width
  172. col_content_split = [ x.strip() for x in col.content.split('\n') ]
  173. cols_sub_rows.append([ x[i:i+col_width].strip() for x in col_content_split
  174. for i in range(0, len(x), col_width) ])
  175. col_border = col_border_next + col_spacing
  176. cols_sub_rows_max = max([len(x) for x in cols_sub_rows])
  177. for n, (col, col_sub_rows) in enumerate(zip(row, cols_sub_rows)):
  178. valign = col.valign
  179. unfilled_rows = cols_sub_rows_max-len(col_sub_rows)
  180. if valign == 0: # top
  181. col_sub_rows = col_sub_rows + ['']*unfilled_rows
  182. elif valign == 1: # center
  183. top_pad = unfilled_rows // 2
  184. bottom_pad = unfilled_rows - top_pad
  185. col_sub_rows = ['']*top_pad + col_sub_rows + ['']*bottom_pad
  186. elif valign == 2: # bottom
  187. col_sub_rows = ['']*unfilled_rows + col_sub_rows
  188. cols_sub_rows[n] = col_sub_rows
  189. sub_rows = [ [None]*row_len for _ in range(cols_sub_rows_max) ]
  190. for n_col, col in enumerate(row):
  191. for i in range(cols_sub_rows_max):
  192. sub_rows[i][n_col] = col.copy(content=cols_sub_rows[n_col][i])
  193. new_rows.append(sub_rows)
  194. rows = new_rows
  195. # Composing final lines
  196. lines = []
  197. row_line = row_symbol[0]*table_width if row_symbol is not None else None
  198. if row_line is not None:
  199. lines.append(row_line)
  200. for sub_rows in rows:
  201. for row in sub_rows:
  202. line = ''
  203. if left_border is not None:
  204. line += left_border
  205. i_col = 0
  206. for col in row:
  207. col_content = col.content
  208. if i_col == 0:
  209. col_border0 = 0
  210. else:
  211. if border is not None:
  212. line += border
  213. col_border0 = cols_border[i_col-1] + col_spacing
  214. i_col += col.span
  215. col_border1 = cols_border[i_col-1]
  216. col_space = col_border1 - col_border0
  217. col_remain_space = col_space-len(col_content)
  218. halign = col.halign
  219. if halign == 0: # left
  220. col_content = col_content + ' '*col_remain_space
  221. elif halign == 1: # center
  222. col_left_pad = col_remain_space // 2
  223. col_right_pad = col_remain_space - col_left_pad
  224. col_content = ' '*col_left_pad + col_content + ' '*col_right_pad
  225. elif halign == 2: # right
  226. col_content = ' '*col_remain_space + col_content
  227. line += col_content
  228. if right_border is not None:
  229. line += right_border
  230. lines.append(line)
  231. if len(sub_rows) != 0 and row_line is not None:
  232. lines.append(row_line)
  233. return '\n'.join(lines)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...