2012-04-15 52 views
1

我有以下代碼生成所需的HTML。但它將它打印在頁面的頂部,而不是我想要的位置。如何從二維列表生成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。但是生成的表格si不插入{0}所在的位置。

您可以查看broken code here.

回答

0

,因爲它那直接打印在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的變量看時,則不應使用printdef output(self):應正確填寫在打印之前不stdout

+0

很抱歉,但你可以使用格式任意順序號裏面:'「{0} {1}」格式(「你好」。 ,'world')==「{1} {0}」。format('world','Hello')' – Rach 2012-04-15 20:23:26

0

與嵌入式環路相比,嵌套環路並不是最佳選擇,與使用內置聯接列表的首選方法相比,即使用.join(),下面的代碼是optimal in most cases,也是更「Python化」的方式

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