task
有時候需要把數(shù)據(jù)(比如csv讹蘑,或者\t分割)轉(zhuǎn)換成html座慰,方便查看翠拣。
jinja安裝
pip install Jinja2
doc: http://docs.jinkan.org/docs/jinja2/index.html
過程
demo數(shù)據(jù)
1心剥,2,3蝉揍,4畦娄,5
6又沾,7熙卡,8,9滑燃,10
把這兩行數(shù)據(jù)渲染在表格里
- 創(chuàng)建your_template.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="cmn-Hans-CN">
<head>
<title>
format
</title>
<meta charset={{ encoding }}>
<style type="text/css">
body{FONT-SIZE: 13px; COLOR: #fffffff; LINE-HEIGHT: 19px;word-spacing:1px}
table{border-collapse:collapse; border: 1px;} th{background: #3e83c9; border:
1px solid #95bce2;font-weight:bold;} td{padding: 4px;border: 1px solid
#95bce2;vertical-align: top;background-color:expression((this.parentElement.sectionRowIndex%2==1)?'#ECF6FC':'#ffffff');
text-aligin:right;} td.name {font-weight:bold;} td.top {background: #d2e9ff;}
td.bg {background: #f0f0f0;}
</style>
</head>
<body>
<table>
<tr>
<th nowrap="">
mt
</th>
<th nowrap="">
flow
</th>
<th nowrap="">
總消費
</th>
<th nowrap="">
關(guān)閉消費
</th>
<th nowrap="">
關(guān)閉占比
</th>
<th nowrap="">
打開占比
</th>
</tr>
{% for item in data %}
<tr>
<td class="bg">
{{ item[0] }}
</td>
<td class="bg">
{{ item[1] }}
</td>
<td class="bg">
{{ item[2] }}
</td>
<td class="bg">
{{ item[3] }}
</td>
<td class="bg">
{{ item[4] }}
</td>
<td class="bg">
{{ item[5] }}
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
- html生成腳本gen_html.py
# encoding=utf-8
import sys
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('./', encoding='utf-8'))
data = []
with open('./data') as f:
for line in f:
line = line.decode('gb18030', 'ignore').strip()
cols = line.split(u'\t')
data.append(cols)
template = env.get_template('your_template.html')
html = template.render(date=date, encoding='utf-8', data=data) # unicode string
print >> sys.stdout, html.encode('utf-8', 'ignore')
python gen_html.py > temp.html
email_to="xxx@xxx.com"
/usr/lib/sendmail -t <<< "To: $email_to
From: yyy@yyy.com
Subject: demo
Content-type: text/html; charset=utf-8
$(cat temp.html)
"