"""Validate semantic numeric rows without fixing a report's number formatting.""" from collections import Counter from decimal import Decimal, InvalidOperation from html.parser import HTMLParser import re class Tables(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.tables = [] self.table = None self.row = None self.cell = None def handle_starttag(self, tag, attrs): if tag == 'table': self.table = [] elif tag == 'tr' and self.table is not None: self.row = [] elif tag in ('td', 'th') and self.row is not None: self.cell = [] def handle_data(self, data): if self.cell is not None: self.cell.append(data) def handle_endtag(self, tag): if tag in ('td', 'th') and self.cell is not None: self.row.append(''.join(self.cell).strip()) self.cell = None elif tag == 'tr' and self.row is not None: self.table.append(self.row) self.row = None elif tag == 'table' and self.table is not None: self.tables.append(self.table) self.table = None def number(text): text = text.strip().replace('\u00a0', ' ').replace('\u202f', ' ') text = re.sub(r'^[¥¥$]\s*', '', text) if re.fullmatch(r'[+-]?\d{1,3}(?:[, ]\d{3})+(?:\.\d+)?', text): text = text.replace(',', '').replace(' ', '') try: value = Decimal(text) except InvalidOperation as exc: raise AssertionError(f'Invalid numeric table cell: {text!r}') from exc assert value.is_finite(), f'Non-finite table cell: {text!r}' return value def assert_top_rows(report, expected): parser = Tables() parser.feed(report) assert_top_tables(parser.tables,expected) def assert_top_tables(tables, expected): aliases = [('price', '价格'), ('carat', '克拉'), ('z', '深度')] candidates = [] for table in tables: for index, row in enumerate(table): headers = [cell.lower().strip() for cell in row] columns = [next((i for i, cell in enumerate(headers) if any(re.search(r'(?