我正在从python列表中生成html代码。
import webbrowser
food_list = [(u'John Doe', 1.73),(u'Jane Doe', 1.73), (u'Jackie O', 1.61)]
def print_html(lista):
print '<table>'
for i in food_list:
print '<tr>'
print '<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>'
print '</tr>'
print' </table>'
code = print_html(food_list)
print code
h = open('list.html','w')
h.write(code)
h.close()
webbrowser.open_new_tab('list.html')
我不能写&#34;代码&#34;到一个用于显示它的html文件。
错误讯息:
h.write(code)
TypeError: expected a character buffer object
我不想硬编码html代码。
它必须如此简单以至于我无法弄明白。
感谢您的建议。
答案 0 :(得分:0)
您可以尝试使用Python自己的html包:
https://pypi.python.org/pypi/html/
from html import HTML
h = HTML()
table = h.table()
food_list = [(u'John Doe', 1.73),(u'Jane Doe', 1.73), (u'Jackie O', 1.61)]
for i in food_list:
row = table.tr
row.td(str(i[0]))
row.td(str(i[1]))
h = open('list.html','w')
h.write(str(table))
h.close()
答案 1 :(得分:0)
它应该像这段代码。
由于您打印了变量,因此没有返回任何内容。由于出现了错误
import webbrowser
food_list = [(u'John Doe', 1.73),(u'Jane Doe', 1.73), (u'Jackie O', 1.61)]
def print_html(food_list):
a=""
a=a+'<table>\n'
for i in food_list:
a=a+'<tr>\n'
a=a+'<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>\n'
a=a+'</tr>\n'
a=a+' </table>\n'
return a
code = print_html(food_list)
print str(code)
h = open('list.html','w')
h.write(str(code))
h.close()
webbrowser.open_new_tab('list.html')
现在运行它并查看
首先显示错误,因为代码变量属于无类型
答案 2 :(得分:0)
您没有返回任何内容,因此您尝试编写无,在函数中写入文件名和列表:
def write_html(lista,f):
with open(f, "w") as f:
f.write('<table>')
for i in lista:
f.write('<tr>')
f.write('<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>')
f.write( '</tr>')
f.write('</table>')
write_html(food_list,"list.html")
webbrowser.open_new_tab('list.html')
输出:
John Doe 1.73
Jane Doe 1.73
Jackie O 1.61
你可以连接然后写,但如果你的目标只是写,那么当你遍历列表时,写起来会更容易。
如果您运行代码,您将在最后看到返回值:
在[27]中:print pri print print_html
In [27]: print print_html(food_list)
<table>
<tr>
<td>John Doe</td><td>1.73</td>
</tr>
<tr>
<td>Jane Doe</td><td>1.73</td>
</tr>
<tr>
<td>Jackie O</td><td>1.61</td>
</tr>
</table>
None # what you are trying to write
你也可以from __future__ import print_function
并使用print写入文件:
def write_html(lista,f):
with open(f, "w") as f:
print('<table>',file=f)
for i in lista:
print('<tr>',file=f)
print('<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>',file=f)
print( '</tr>',file=f)
print(' </table>',file=f)
或者使用python2语法:
def write_html(lista,f):
with open(f, "w") as f:
print >>f, '<table>'
for i in lista:
print >>f,'<tr>'
print >>f, '<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>'
print >>f, '</tr>'
print >>f,' </table>'