首页 > 解决方案 > 使用 Python 为特定行创建一个包含多列的 HTML 表

问题描述

我写了这段代码:

tr = ""
for author, projects in data.iteritems():
    tr + = "<tr><td>{}</td>".format(author)
    for project, branches in projects.iteritems():
        tr += "<td>{}</td>".format(project)
        for branch in branches:
            tr += "<td>{}</td>".format(branch)
    tr += </td></tr>
end = "</table>"

我有这个数据集

{
'user_one': {'project_a': ['branch_1', 'branch_2'],
          'project_b': ['branch_1']},
'user_two': {'project_x': ['branch_x1', 'branch_b'] }
}

我想打印如下表:

+-------------------------------------------+
|    User    |    Project    |    Branch    |
+------------+---------------+--------------+
|  user_one  |   project_a   |   branch_1   |
+------------+---------------+--------------+
|            |               |   branch_2   |
+------------+---------------+--------------+
|            |   project_b   |   branch_1   |
+------------+---------------+--------------+
|  user_two  |  project_x    |   branch_x1  |
+------------+---------------+--------------+
|            |               |   branch_b   |
+------------+---------------+--------------+

如果它的单个项目工作正常,但当涉及多个项目时,它不会。我可以使用 PrettyTable 获得结果,但因为我希望 project_a、_b、_x 等成为超链接。我在使用 PrettyTable 时无法实现,所以我开始编写自己的基于数据的 html 生成器。

标签: pythonhtml-tabletablecolumn

解决方案


除了琐碎的 HTML(可能不是表格),我建议使用模板库

我会选择Jinja2。它的语法非常简单和直观(如果您见过任何其他模板语言),它有很好的文档记录,并且非常流行(=更多 SO 支持)。

呈现表格的示例。

<table class="table table-striped">
    <thead><tr>
        <th>One</th>
        <th>Two</th>
        <th>Three</th>
        <th>Four</th>
    </tr></thead>
    <tbody>
    {% for row in tabular_data %}
    <tr>
        <td>{{ row.one }}</td>
        <td>{{ row.two }}</td>
        <td>{{ row.three }}</td>
        <td>{{ row.four }}</td>
    </tr>
    {% endfor %}
    </tbody>
</table>

如果您使用的是 Web 框架,它可能是开箱即用的,如果没有,则只需几行即可渲染它:

from jinja2 import Environment, FileSystemLoader  # pip install Jinja2

env = Environment(loader=FileSystemLoader("/path/to/templates/folder")
template = env.get_template("TableTemplate.html")  # the template file name
html = template.render(**context_data)

context_data包含所需数据的字典在哪里。在上面的示例中,它需要一个tabular_data字段来保存具有属性的对象(或字典)数组onetwo...:

context_data = {
    # Row = namedtuple("Row", ["one", "two", "three", "four"])
    'tabular_data': [             
        Row(1, 2, 3, 4), 
        Row("a", "b", "c", "d"),
        ..., 
    ]
}

推荐阅读