使用python lis的html文档中的表

2024-05-03 16:48:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为new_list的嵌套数据列表,它来自python中的csv文件,我需要将其放入html文档中的一个简单表中。

[['Jason'、'Brown'、'Leeds'、'40'、['Sarah'、'Robinson'、'Bristol'、'32'、['Carlo'、'Baldi'、'Manchester'、'41']]

我已经设法在Python控制台中为表标题编写了html,但是不知道如何引用列表中的内容-例如,在<tr>标记之间放置什么来填充行。这就是我目前所拥有的:

display = open("table.html", 'w')
display.write("""<HTML>
<body>
    <h1>Attendance list</h1>
    <table>
        <tr></tr>
        <tr></tr>
    </table>
</body>
</HTML>""")

非常感谢提前!


Tags: 文件csv数据文档列表newhtmldisplay
3条回答

简单的字符串和列表操作。

html = """<HTML>
<body>
    <h1>Attendance list</h1>
    <table>
        {0}
    </table>
</body>
</HTML>"""

items = [['Jason', 'Brown', 'Leeds', '40'], ['Sarah', 'Robinson', 'Bristol', '32'], ['Carlo', 'Baldi', 'Manchester', '41']]
tr = "<tr>{0}</tr>"
td = "<td>{0}</td>"
subitems = [tr.format(''.join([td.format(a) for a in item])) for item in items]
# print html.format("".join(subitems)) # or write, whichever

输出:

<HTML>
<body>
    <h1>Attendance list</h1>
    <table>
        <tr><td>Jason</td><td>Brown</td><td>Leeds</td><td>40</td></tr><tr><td>Sarah</td><td>Robinson</td><td>Bristol</td><td>32</td></tr><tr><td>Carlo</td><td>Baldi</td><td>Manchester</td><td>41</td></tr>
    </table>
</body>
</HTML>

enter image description here

这项工作的正确工具是一个模板引擎。很明显,您有一个HTML模板,并且您希望将数据适当地插入到指定占位符中的HTML中。

使用^{}的示例:

In [1]: from mako.template import Template
In [2]: rows = [['Jason', 'Brown', 'Leeds', '40'], ['Sarah', 'Robinson', 'Bristol', '32'], ['Carlo', 'Baldi', 'Manchester', '41']]
In [3]: template = """
        <html>
            <body>
                <table>
                     % for row in rows:
                     <tr>
                          % for cell in row:
                          <td>${cell}</td>
                          % endfor
                     </tr>
                     % endfor
                </table>
            </body>
        </html>"""

In [4]: print(Template(template).render(rows=rows))
<html>
    <body>
        <table>
            <tr>
                 <td>Jason</td>
                 <td>Brown</td>
                 <td>Leeds</td>
                 <td>40</td>
            </tr>
            <tr>
                 <td>Sarah</td>
                 <td>Robinson</td>
                 <td>Bristol</td>
                 <td>32</td>
            </tr>
            <tr>
                 <td>Carlo</td>
                 <td>Baldi</td>
                 <td>Manchester</td>
                 <td>41</td>
            </tr>
        </table>
    </body>
</html>

它不简单易读吗?而且,作为奖励,没有直接和手动的HTML字符串操作。

我认为可以从内置Python模块string formatting开始。如果您需要它用于较低的Python版本,它自2.5版以来没有太大的变化。

通常,web/html内容由一些更复杂的web框架处理,比如DjangoTurboGears,但这可能不是您的用例。

相关问题 更多 >