|
| 1 | +import csv |
| 2 | +import json |
| 3 | +from collections import defaultdict |
| 4 | +from io import StringIO |
| 5 | +from pathlib import Path |
| 6 | +from pprint import pprint |
| 7 | + |
| 8 | + |
| 9 | +class TableDecoder: |
| 10 | + _register: dict[str, int] = {} |
| 11 | + |
| 12 | + @classmethod |
| 13 | + def __init_subclass__(cls, *, extension, **kwargs): |
| 14 | + super().__init_subclass__(**kwargs) |
| 15 | + |
| 16 | + cls._register[extension] = cls |
| 17 | + |
| 18 | + @classmethod |
| 19 | + def create(cls, name): |
| 20 | + decoder_class = cls._register[name] |
| 21 | + return decoder_class() |
| 22 | + |
| 23 | + @classmethod |
| 24 | + def decoders(cls): |
| 25 | + return list(cls._register.keys()) |
| 26 | + |
| 27 | + @staticmethod |
| 28 | + def decode(text): |
| 29 | + raise NotImplementedError |
| 30 | + |
| 31 | + |
| 32 | +class JsonTableEncoder(TableDecoder, extension='json'): |
| 33 | + |
| 34 | + @staticmethod |
| 35 | + def decode(text): |
| 36 | + objs = json.loads(text) |
| 37 | + table = defaultdict(list) |
| 38 | + for obj in objs: |
| 39 | + for k, v in obj.items(): |
| 40 | + table[k].append(v) |
| 41 | + return dict(table) |
| 42 | + |
| 43 | + |
| 44 | +class CsvTableEncoder(TableDecoder, extension='csv'): |
| 45 | + @staticmethod |
| 46 | + def decode(text): |
| 47 | + with StringIO(text) as csv_stream: |
| 48 | + reader = csv.DictReader(csv_stream) |
| 49 | + table = defaultdict(list) |
| 50 | + for row in reader: |
| 51 | + for k, v in row.items(): |
| 52 | + table[k].append(v) |
| 53 | + return dict(table) |
| 54 | + |
| 55 | + |
| 56 | +def load_table(filepath): |
| 57 | + filepath = Path(filepath) |
| 58 | + text = filepath.read_text() |
| 59 | + extension = filepath.suffix.removeprefix('.') |
| 60 | + decoder = TableDecoder.create(extension) |
| 61 | + table = decoder.decode(text) |
| 62 | + return table |
| 63 | + |
| 64 | + |
| 65 | +def main(): |
| 66 | + print(TableDecoder.decoders()) |
| 67 | + table = load_table('table.json') |
| 68 | + pprint(table) |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + main() |
0 commit comments