python HTML展示表格数据(有合并的单元格)
1个回答
展开全部
拷贝一下代码并保存到本地,然后运行它,再打开那个Demo的链接就可以看到效果了
#!/usr/bin/env python3
from collections import OrderedDict
from os.path import dirname, abspath, join as joinpath
L = [(1,2),(1,2),(1,3),(2,4),(2,5)]
column_names = ('列名', '数据')
odict = OrderedDict()
for k, v in L:
if k not in odict:
odict[k] = [v]
else:
odict[k].append(v)
sa = '''
<!DOCTYPE HTML>
<meta charset="UTF-8">
<html>
<body>
<table border="1" cellpadding="10">
<tr>
<th>{}</th>
<th>{}</th>
</tr>
'''.format(*column_names)
sc = '''
</table>
</body>
</html>
'''
sb = []
tdform = '<td align="center">{}</td>'.format
for k, v in odict.items():
if len(v) == 1:
sb.append('<tr>')
sb.append(tdform(k))
sb.append(tdform(v))
sb.append('</tr>')
else:
for i, subv in enumerate(v):
sb.append('<tr>')
if i == 0:
sb.append('<td rowspan="{}" align="center">{}</td>'.format(
len(v), k))
sb.append(tdform(subv))
sb.append('</tr>')
fn = 'table.html'
ss = sa + '\n'.join(sb) + sc
try:
from bs4 import BeautifulSoup
soup = BeautifulSoup(ss)
ss = soup.prettify()
except:
pass
with open(fn, 'w') as f:
f.write(ss)
print(ss)
print('Demo: file://'+joinpath(abspath(dirname(__file__)), fn))
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询