-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml_parser.py
79 lines (64 loc) · 2.37 KB
/
html_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class HTML(object):
def __init__(self):
self.body = ''
class Table(object):
def __init__(self, attrs=None):
self.table = ''
self.attr_len = 0
if attrs is not None:
self.table_create(attrs)
def __str__(self):
return self.table + '</table>'
def table_create(self, attrs):
self.table = '<table style="width:100%">'
self.attr_len = len(attrs)
self._table_add_item(attrs, head=True)
def table_add(self, attrs):
self._table_add_item(attrs)
def _table_add_item(self, attrs, head=False):
if len(attrs) == self.attr_len:
pass
else:
raise TypeError('Attribution of the table is not correct')
if isinstance(attrs, list):
self.table += '<tr>'
for item in attrs:
if head:
self.table += '<th>{0}</th>'.format(str(item))
else:
self.table += '<td>{0}</td>'.format(str(item))
self.table += '</tr>'
elif isinstance(attrs, str):
self.table += '<tr>'
if head:
self.table += '<th>{0}</th>'.format(str(attrs))
else:
self.table += '<td>{0}</td>'.format(str(attrs))
self.table += '</tr>'
else:
raise TypeError('Attribution of the table is not correct')
def __repr__(self):
return '<html>' + '<head>' + self.style() + '</head>' + \
'<body>' + self.body + '</body>' + '<html>'
@staticmethod
def title(text):
return '<h1>{0}</h1>'.format(str(text))
@staticmethod
def _table_type(tp=None):
if tp is not None:
table_type = tp
else:
table_type = 'table, th, td {border: 1px solid black;}'
return table_type
def add(self, text):
self.body += '<p>{0}</p>'.format(str(text))
def style(self, tp='', table_type=None):
return '<style>' + tp + self._table_type(table_type) + '</style>'
html = HTML()
title1 = html.title('This is a test table')
html.add(title1)
html.add('Do not tell anybody!')
table = html.Table(['name', 'age', 'gender'])
table.table_add(['Alfred', '27', 'M'])
html.add(table)
print str(html)