用Python實現CSV格式文件轉換爲HTML文件[Python3程序開發指南實現]

#!/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("&","&amp;")
    text=text.replace("<","&lt;")
    text=text.replace(">","&gt;")
    return text
main()#執行整個程序


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章