From 704290b1a28c3a609823ed2f8df37a06480b1013 Mon Sep 17 00:00:00 2001 From: Mike Bloy Date: Sat, 28 Oct 2023 18:55:25 -0500 Subject: [PATCH] ex35 --- ex35.py | 7 ++++++ tableformat.py | 67 ++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 ex35.py diff --git a/ex35.py b/ex35.py new file mode 100644 index 0000000..eb24ea7 --- /dev/null +++ b/ex35.py @@ -0,0 +1,7 @@ +import reader +import stock +import tableformat + +portfolio = reader.read_csv_as_instances("Data/portfolio.csv", stock.Stock) +formatter = tableformat.create_formatter("text") +tableformat.print_table(portfolio, ["name", "shares", "price"], formatter) diff --git a/tableformat.py b/tableformat.py index 6903b9e..6b72d22 100644 --- a/tableformat.py +++ b/tableformat.py @@ -1,5 +1,62 @@ -def print_table(objects, attributes): - print(*("{: >10}".format(attr) for attr in attributes)) - print(*("{:->10}".format("") for _ in attributes)) - for obj in objects: - print(*("{: >10}".format(getattr(obj, attr, "")) for attr in attributes)) +class TableFormatter: + def headings(self, headers): + raise NotImplementedError() + + def row(self, rowdata): + raise NotImplementedError() + + +class TextTableFormatter: + def _printer(self, data): + print(*("{: >10}".format(value) for value in data)) + + def headings(self, headers): + self._printer(headers) + print(*("{:->10}".format("") for _ in headers)) + + def row(self, rowdata): + self._printer(rowdata) + + +class CSVTableFormatter: + def _printer(self, data): + print(",".join(str(value) for value in data)) + + def headings(self, headers): + return self._printer(headers) + + def row(self, rowdata): + return self._printer(rowdata) + + +class HTMLTableFormatter: + def _cell(self, value, tag): + return f"<{tag}>{value}" + + def _printer(self, data, tag): + line = f"{' '.join(self._cell(str(value), tag) for value in data)}" + print(line) + + def headings(self, headers): + return self._printer(headers, "th") + + def row(self, rowdata): + return self._printer(rowdata, "td") + + +def create_formatter(name): + formatters = { + "text": TextTableFormatter, + "csv": CSVTableFormatter, + "html": HTMLTableFormatter, + } + formatter = formatters.get(name, None) + if not name: + raise ValueError(f'formatter named "{name}" not implemented') + return formatter() + + +def print_table(records, fields, formatter): + formatter.headings(fields) + for record in records: + formatter.row([getattr(record, fieldname) for fieldname in fields])