#打印一行
#不能使用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()#执行整个程序