1. 程式人生 > >通過python將xml檔案轉換成html檔案

通過python將xml檔案轉換成html檔案

#資料型別的轉換
def main():
    maxwidth = 100  #用於規範字段的長度
    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()

maxwidth 用於規範字段的長度,一旦比這個長度長的欄位,我們可以通過用省略號來替代後面的內容
count 用於對檔案中的顏色的改變,斑馬紋的實現。
上面的程式碼中的print_start(),print_line(),print_end()三個函式是我們自己的設定的函式,程式碼在後面
print_start() 函式用於輸入開頭
print_end() 函式用於輸入結尾
print_line() 將該行以html的形式輸出

def print_start():
    print("<table border='1'>")
#用於檔案的開始頭拼接
def print_end():
    print("</table>")
#用於檔案的結尾拼接

上面兩個是用來減少函式之間的關聯性,雖然在函式中新增print(…)也可以,
但是這樣可以更加規範,以後修改也比較容易,對之後的運維提供極大的方便,
通過修改函式,可以將所有的頭尾一起修改。

def print_line(line,color,maxwidth):
    print("<tr bgcolor='{0}'>".format(color))
    fields = extrace_fields(line)
    for
 field in fields:
        if not field:
            print("<td></td>")
        else:
            number = field.replace(",","")
            #這裡把”,“改成”“的意義是為了將數值1,000轉換為1000的格式
        try:
            x = float(number)
            print("<td align='right'>{0}</td>33".format(round(x)))
        except ValueError:
            field =field.title() 
            '''
            用於註釋
            title函式是用來將字串的首字母大寫處理            
            str = "this is string example from runoob....wow!!!"
            請注意,非字母后的第一個字母將轉換為大寫字母:
            txt = "hello b2b2b2 and 3g3g3g"
            print(txt.title())    #Hello B2B2B2 And 3G3G3G
            '''

            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>")

這段程式是將通過for遍歷檔案,提取出裡面的值,將裡面的值進行規範化 然後通過需要的html格式通過format拼接,最後顯示出來。
通過try的異常捕捉,我們可以將檔案中的數字與字串分開處理,數字通過flaot進行小數格式化,字串通過title格式化
這又體現了python語言通過try捕獲異常的靈活性
為什麼不再讀取的時候直接通過replace進行分割字串?
因為這是為了防止出現,分號中間有”,“ 使檔案不正確分割,導致程式出現錯誤,所以,我們要在print_line中在進行分割,減少錯誤的產生
extrace_fields(line)是自定義函式,函式的作用是將欄位串進行分割

def extrace_fields(line):
    fields =[]
    field = ''
    quote = None
    for c in line:
        if c in "\"":    
            if quote is None:  #start of quoted string
                quote = c
            elif quote == c: #end of quoted string
                quote = None
            else:
                field += c #other quote inside quoted string
            continue 
        if quote is None and c == ","#end of a field
            fields.append(field)
            field =''
        else:
            field += c  #accumulating a field
    if field:
        fields.append(field)#adding the last field
    return fields
def escape_html(text):
    text = text.replace('&','&amp;')
    text = text.replace('<',"&lt;")
    text = text.replace(">","&gt;")
    return text

通過替換函式將'<','>'替換成html可識別的實體字元,不替換的話 html會將'<','>'大於小於符號識別為尖括號<>