MCPcopy Create free account
hub / github.com/chatdoc-com/OCRFlux / table_html2matrix

Function table_html2matrix

ocrflux/table_format.py:73–123  ·  view source on GitHub ↗
(html_table)

Source from the content-addressed store, hash-verified

71 return "".join(html_table)
72
73def table_html2matrix(html_table):
74 soup = BeautifulSoup(html_table, 'html.parser')
75 table = soup.find('table')
76 rownum = len(table.find_all('tr'))
77 colnum = 0
78 tr = table.find_all('tr')[0]
79 for td in tr.find_all('td'):
80 colnum += td.get('colspan', 1)
81 matrix = [[None for _ in range(colnum)] for _ in range(rownum)]
82
83 rid = 0
84 for tr in table.find_all('tr'):
85 cid = 0
86 for td in tr.find_all('td'):
87 for c in range(cid, colnum):
88 if matrix[rid][c] is None:
89 break
90 cid = c
91 rowspan = td.get('rowspan', 1)
92 colspan = td.get('colspan', 1)
93 cell_text = td.get_text(strip=True)
94 for r in range(rid,rid+rowspan):
95 if r >= rownum:
96 raise Exception('rownum not match')
97 for c in range(cid,cid+colspan):
98 if c >= colnum:
99 raise Exception('colnum not match')
100 if matrix[r][c] is not None:
101 raise Exception('cell not match')
102 if r == rid and c == cid:
103 matrix[r][c] = cell_text
104 elif r == rid:
105 matrix[r][c] = '<l>'
106 elif c == cid:
107 matrix[r][c] = '<t>'
108 else:
109 matrix[r][c] = '<lt>'
110 cid += colspan
111 rid += 1
112
113 matrix_table = ['<table>']
114 for rid in range(rownum):
115 matrix_table.append('<tr>')
116 for cid in range(colnum):
117 matrix_table.append('<td>')
118 cell_text = matrix[rid][cid]
119 matrix_table.append(cell_text)
120 matrix_table.append('</td>')
121 matrix_table.append('</tr>')
122 matrix_table.append('</table>')
123 return "".join(matrix_table)
124
125trans_func = {
126 "html2matrix": table_html2matrix,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected