您的位置:首页 > 编程语言 > Python开发

用Python实现CSV格式文件转换为HTML文件[Python3程序开发指南实现]

2015-03-29 15:20 836 查看
#!/usr/bin/env python3
def main():
maxwidth=100#控制cell长度
print_start()
count=0
while True:
try:
#控制每行显示的颜色,首行绿色
#偶数行为白色
#其他行显示***
line=input()
if count==0:
color="lightgreen"
elif count%2:
color="white"
else:
color="lightyellow"

#输出每一行
print_line(line,color,maxwidth)
count+=1
except EOFError:
break
print_end()

def print_start():
print("<table border='1'>")

def print_end():
print("</table>")

#打印一行
#不能使用str.split(",")将每行分隔成不同字段,因为引号内也可能包含逗号
#因而在extract_field()中实现这一功能
def print_line(line,color,maxwidth):
print("<tr bgcolor='{0}'>".format(color))#打印行首
fields=extract_fields(line)
for field in fields:
if not field:
print("<td></td>")
else:
#表示的数字可能含有字符",",将其替换
number=field.replace(",","")
try:
x=float(number)#
print("<td align='right'>{0:d}</td>".format(round(x)))#打印行尾
#round():四舍五入
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]))
print("<td>{0}</td>".format(field))#打印行尾
print("</tr>")

#CSV格式文件用","划分字段,将其改变为用空格划分字段
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 escape_html(text):
text=text.replace("&","&")
text=text.replace("<","<")
text=text.replace(">",">")
return text
main()#执行整个程序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: