如何从二维列表生成HTML表?

时间:2012-04-15 20:03:18

标签: python html list html-table

我有以下代码生成所需的HTML。但它会将其打印在页面顶部,而不是我想要的位置。

def fixText(self,text):
    row = []
    z = text.find(',')

    if z == 0: row.append('')
    else:      row.append(text[:z])

    for x in range(len(text)):
        if text[x] != ',': pass
        else:
            if x == (len(text)-1): row.append('')
            else:
                if ',' in text[(x+1):]:
                    y = text.find(',', (x+1))
                    c = text[(x+1):y]
                else:
                    c = text[(x+1):]
                    row.append(c)
    return row

def output(self):
    output = ""
    fob=open('files/contacts.txt','r')
    tup = []

    while 1:
        text = fob.readline()

        if text == "": break
        else: pass

        if text[-1] == '\n':
            text = text[:-1]
        else: pass

        row = self.fixText(text)
        tup.append(row)

    output = tup.sort(key=lambda x: x[0].lower())

    _list1 = len(tup)
    i = 0
    table = ""

    while i < _list1:
        j = 0 #need to reset j on each iteration of i
        _list2 = len(tup[i])
        print("<tr>")

        while j < _list2:
            print("<td>" + tup[i][j] + "</td>")
            j += 1

        print("</tr>")
        i += 1

    return output

正如您所看到的,我有一个打印出HTML代码的嵌套循环。这很好用,但是当我尝试将它注入我的模块化站点时,它会在页面顶部打印出来。我的预感是以下代码是我需要改变的部分。

#!/usr/local/bin/python3

print('Content-type: text/html\n')

import os, sys
import cgitb; cgitb.enable()

sys.path.append("classes")

from Pagedata import Pagedata
Page = Pagedata()

print(Page.doctype())
print(Page.head())
print(Page.title("View Contact"))
print(Page.css())

html='''</head>
<body>
<div id="wrapper">
    <div id="header">
        <div id="textcontainer">{1}</div>
    </div>
    <div id="nav">{2}</div>
    <div id="content">
        <h2>Heading</h2>
        <h3>Sub Heading Page 2</h3>
        <table>
            <tbody>
                {0}
            </tbody>
        </table>    
    </div>
<div>
<div id="footer">{3}</div>
</body>
</html>'''.format(Page.output(),Page.header(),Page.nav(),Page.footer())

print(html)

我的课程页面上还有其他功能,例如headerfooter等,可以正常使用。

例如,页脚已正确插入div#footer。但是生成的表格未插入{0}所在的位置。

您可以查看broken code here.

2 个答案:

答案 0 :(得分:0)

您不应在print内使用def output(self):,因为它会在sys.stdout

上查看时直接打印
table = ""
while i < _list1:
    j = 0#need to reset j on each iteration of i
    _list2 = len(tup[i])
    table += "<tr>"
    while j < _list2:
        table=+"<td>" + tup[i][j] + "</td>"
        j += 1
    table += "</tr>"
    i += 1
return table

在打印之前,您应该正确填充html变量stdout

答案 1 :(得分:0)

与内置的首选加入列表方法相比,嵌套循环不是最优的,即使用.join(),以下代码为optimal in most cases,并且更多&#34; pythonic&#34 ;方式

table = ""
while i < _list1:
    table += "<tr><td>{0}</td></tr>".format("</td><td>".join(tup[i]))
    i += 1
return table