代码转自:Python3程序开发指南(第二版)
稍有改动
data.csv
"country","2000","2001",2002,2003
"ANTIGUA",0,0,0,0
"CHINA",100,200,200,300.122
"BAHAMAS",4,5,22,33
csv2html.py
#coding=utf-8
import sys
def escape_html(text):
text=text.replace('&','&')
text=text.replace('<','<')
text.replace('>', '>')
return text
def extract_fields(line):
fields=[]
field=""
quote=None
for c in line:
if c in "\"'":
if quote is None:
quote=c
elif quote==c:
quote=None
else:
field+=c
continue
if quote is None and c==",":
fields.append(field)
field=""
else:
field+=c
if field:
fields.append(field)
return fields
def print_line(line,color,maxwidth):
tr_start=""
tr_end=""
tr_start+="<tr bgcolor='{0}'>".format(color)
fields=extract_fields(line)
td_mid=""
for field in fields:
if not field:
td_mid+="<td></td>"
else:
number=field.replace(",","")
try:
x=float(number)
td_mid+="<td alig='right'>{0:d}</td>".format(round(x))
except ValueError:
field=field.title()
#field=field.replace("And",'and')
if len(field)<maxwidth:
field=escape_html(field)
else:
field="{0}...".format(escape_html(field[:maxwidth]))
td_mid+="<td>{0}</td>".format(field)
tr_end+="</tr>"
return tr_start+td_mid+tr_end
def print_start():
return "<table border='1'>"
def print_end():
return "</table>"
def main(filename):
maxwidth=5
start=print_start()
count=0
color=""
str_temp=''
lines=open(filename).readlines()
for line in lines:
if count==0:
color="lightgreen"
elif count%2:
color="white"
else:
color="lightyellow"
str_temp+=print_line(line,color,maxwidth)
count +=1
import os
end=print_end()
result="%s %s %s" %(start,str_temp,end)
prefix,*temp=os.path.splitext(filename)
with open(prefix+'.html','w') as f:
f.write(result)
if __name__ == '__main__':
main(sys.argv[1])
命令行执行:
python3 csv2html.py data.csv
生成data.html文件