Skip to content

Instantly share code, notes, and snippets.

@junaid1460
Last active January 7, 2023 20:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save junaid1460/4b37fccfcaef27ac83653eacdcc0fe9b to your computer and use it in GitHub Desktop.
Save junaid1460/4b37fccfcaef27ac83653eacdcc0fe9b to your computer and use it in GitHub Desktop.
Jupyter HTML Table class, Pythonic way of creating Table for jupyter
from IPython.display import HTML, display
class Tag:
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "<%s>%s</%s>"%(self.name, str(self.value), self.name)
class Linear:
def __init__(self, data):
self.data = list(data)
def __repr__(self):
return ''.join(list(map(str, self.data)))
class Table:
def __init__(self, cols):
self.header = list(iter(cols))
self.len = len(self.header)
self.contents = []
self.compiled = False
def add(self, data):
if(len(data) != self.len):
raise AssertionError
self.contents.append(data)
self.compiled = False
def __repr__(self):
if self.compiled:
return self.compiledHTML
header = Tag("tr", Linear(list(map(lambda x:Tag('th', x), self.header))))
contents = []
for c in self.contents:
contents += [ Tag("tr", Linear(list(map(lambda x:Tag('td', x), c))))]
self.compiledHTML = str(Tag('Table', Linear((header, Linear(contents)))))
self.compiled = True
return self.compiledHTML
def display_notebook(self):
display(HTML(str(self)))
from jupyter_html_table import Table
x = Table(('col1', 'col2'))
x.add((32, 323))
x.add((32,23))
x.display_notebook()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment