如何将python列表导入到HTML(Python)中的表(tr)

时间:2018-05-22 09:35:05

标签: python html

我在python中有一个列表,如何将它传递给Python中的 HTML 表。

list1 = [['Career', 'school', 5, 'A'], ['Career', 'higher', 4, 'A'], ['Career', 'college', 3, 'A'], ['Edu', 'Blr', 20, 'A']]

 html =  """\<html><head><style>table, th, td {border: 1px solid black;border-collapse: collapse;}th, td {padding: 5px;text-align: left;}</style></head><table style="width:30%"><tr><th>Category</th><th>Sub-Category</th><th>Sessions</th><th>Org_name</th></tr><tr># The list should print here </tr></table></body></html> """

输出应该在表格中

Category|Sub-Category|Sessions|Org_name Career |School |5 |A Career |Higher |4 |A Career |College |3 |A Edu |Blr |20 |A

请帮帮我。

4 个答案:

答案 0 :(得分:1)

这是一个没有任何第三方库的简单解决方案:

list1 = [['Career', 'school', 5, 'A'], ['Career', 'higher', 4, 'A'], ['Career', 'college', 3, 'A'], ['Edu', 'Blr', 20, 'A']]
headers = ['Category', 'Sub-Category', 'Sessions', 'Org_name']
style = """
 td, th {
      border: 1px solid black;
    }
"""
template = """
<html>
  <style>
    {}
  </style>
  <body> 
    <table>   
    {}
    </table>
  </body>
</html>
""".format(style, '\t<tr>'+'\n'.join('\t\t<th>{}</th>'.format(i) for i in headers)+'\n\t</tr>'+'\n'.join('\t<tr>'+'\n'.join('\t\t<td>{}</td>'.format(c) for c in i)+'\n\t</tr>' for i in list1[1:])) 
with open('test_file.html', 'w') as f:
  f.write(template)

在浏览器中打开test_file.html时,会生成以下结果:

https://tools.ietf.org/html/rfc2437#section-9.2.1

答案 1 :(得分:0)

这样做:

{% for lists in list1 %}
    <tr>
    {%for li in lists %}
    <td>{{li}}</td>
    {% endfor %}
    </tr>
{% endfor %}

答案 2 :(得分:0)

如果你只是在Python程序中寻找一串HTML,我能想到的最简单的方法就是使用Pandas及其to_html方法:

import pandas as pd
df = pd.DataFrame(list1)
df.columns = ['Category', 'Sub-Category', 'Sessions', 'Org_name']
html = df.to_html(index=False)

答案 3 :(得分:0)

df=pd.DataFrame(list1,columns=["Category","Sub-Category","Sessions","Org_name"])

print(df.to_html()) #it will print html tags for the df

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Category</th>
      <th>Sub-Category</th>
      <th>Sessions</th>
      <th>Org_name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Career</td>
      <td>school</td>
      <td>5</td>
      <td>A</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Career</td>
      <td>higher</td>
      <td>4</td>
      <td>A</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Career</td>
      <td>college</td>
      <td>3</td>
      <td>A</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Edu</td>
      <td>Blr</td>
      <td>20</td>
      <td>A</td>
    </tr>
  </tbody>
</table>