在Python中将CSV转换为HTML表

问题描述 投票:5回答:5

我正在尝试从.csv文件中获取数据并导入到python中的HTML表中。

这是csv文件https://www.mediafire.com/?mootyaa33bmijiq

语境: csv包含来自足球队的数据[年龄组,回合,反对,团队得分,反对分数,位置]。我需要能够选择特定的年龄组,并且只在单独的表中显示这些细节。

这就是我到目前为止所有的......

infile = open("Crushers.csv","r")

for line in infile:
    row = line.split(",")
    age = row[0]
    week = row [1]
    opp = row[2]
    ACscr = row[3]
    OPPscr = row[4]
    location = row[5]

if age == 'U12':
   print(week, opp, ACscr, OPPscr, location)
python html html-table import-from-csv
5个回答
1
投票

在开始打印所需的行之前,输出一些HTML以设置适当的表结构。

找到要打印的行时,以HTML表格格式输出。

# begin the table
print("<table>")

# column headers
print("<th>")
print("<td>Week</td>")
print("<td>Opp</td>")
print("<td>ACscr</td>")
print("<td>OPPscr</td>")
print("<td>Location</td>")
print("</th>")

infile = open("Crushers.csv","r")

for line in infile:
    row = line.split(",")
    age = row[0]
    week = row [1]
    opp = row[2]
    ACscr = row[3]
    OPPscr = row[4]
    location = row[5]

    if age == 'U12':
        print("<tr>")
        print("<td>%s</td>" % week)
        print("<td>%s</td>" % opp)
        print("<td>%s</td>" % ACscr)
        print("<td>%s</td>" % OPPscr)
        print("<td>%s</td>" % location)
        print("</tr>")

# end the table
print("</table>")

11
投票

首先安装大熊猫:

pip install pandas

然后运行:

import pandas as pd

columns = ['age', 'week', 'opp', 'ACscr', 'OPPscr', 'location']
df = pd.read_csv('Crushers.csv', names=columns)

# This you can change it to whatever you want to get
age_15 = df[df['age'] == 'U15']
# Other examples:
bye = df[df['opp'] == 'Bye']
crushed_team = df[df['ACscr'] == '0']
crushed_visitor = df[df['OPPscr'] == '0']
# Play with this

# Use the .to_html() to get your table in html
print(crushed_visitor.to_html())

你会得到类似的东西:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>age</th>
      <th>week</th>
      <th>opp</th>
      <th>ACscr</th>
      <th>OPPscr</th>
      <th>location</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>34</th>
      <td>U17</td>
      <td>1</td>
      <td>Banyo</td>
      <td>52</td>
      <td>0</td>
      <td>Home</td>
    </tr>
    <tr>
      <th>40</th>
      <td>U17</td>
      <td>7</td>
      <td>Aspley</td>
      <td>62</td>
      <td>0</td>
      <td>Home</td>
    </tr>
    <tr>
      <th>91</th>
      <td>U12</td>
      <td>7</td>
      <td>Rochedale</td>
      <td>8</td>
      <td>0</td>
      <td>Home</td>
    </tr>
  </tbody>
</table>

0
投票

首先进口一些:

import csv
from html import escape
import io

现在构建块 - 让我们创建一个用于读取CSV的函数和另一个用于制作HTML表的函数:

def read_csv(path, column_names):
    with open(path, newline='') as f:
        # why newline='': see footnote at the end of https://docs.python.org/3/library/csv.html
        reader = csv.reader(f)
        for row in reader:
            record = {name: value for name, value in zip(column_names, row)}
            yield record

def html_table(records):
    # records is expected to be a list of dicts
    column_names = []
    # first detect all posible keys (field names) that are present in records
    for record in records:
        for name in record.keys():
            if name not in column_names:
                column_names.append(name)
    # create the HTML line by line
    lines = []
    lines.append('<table>\n')
    lines.append('  <tr>\n')
    for name in column_names:
        lines.append('    <th>{}</th>\n'.format(escape(name)))
    lines.append('  </tr>\n')
    for record in records:
        lines.append('  <tr>\n')
        for name in column_names:
            value = record.get(name, '')
            lines.append('    <td>{}</td>\n'.format(escape(value)))
        lines.append('  </tr>\n')
    lines.append('</table>')
    # join the lines to a single string and return it
    return ''.join(lines)

现在就把它放在一起:)

records = list(read_csv('Crushers.csv', 'age week opp ACscr OPPscr location'.split()))

# Print first record to see whether we are loading correctly
print(records[0])
# Output:
# {'age': 'U13', 'week': '1', 'opp': 'Waterford', 'ACscr': '22', 'OPPscr': '36', 'location': 'Home'}

records = [r for r in records if r['age'] == 'U12']

print(html_table(records))
# Output:
# <table>
#   <tr>
#     <th>age</th>
#     <th>week</th>
#     <th>opp</th>
#     <th>ACscr</th>
#     <th>OPPscr</th>
#     <th>location</th>
#   </tr>
#   <tr>
#     <td>U12</td>
#     <td>1</td>
#     <td>Waterford</td>
#     <td>0</td>
#     <td>4</td>
#     <td>Home</td>
#   </tr>
#   <tr>
#     <td>U12</td>
#     <td>2</td>
#     <td>North Lakes</td>
#     <td>12</td>
#     <td>18</td>
#     <td>Away</td>
#   </tr>
#   ...
# </table>

几点说明:

  • csv.reader比线分割效果更好,因为它还处理引用值,甚至引用带换行符的值
  • html.escape用于转义可能包含字符<>的字符串
  • 使用dicts比使用元组更容易
  • 通常CSV文件包含标题(第一行包含列名),可以使用csv.DictReader轻松加载;但是Crushers.csv没有标题(数据从第一行开始)所以我们自己在函数read_csv中构建了dicts
  • 函数read_csvhtml_table都是通用的,因此它们可以处理任何数据,列名称不会“硬编码”到它们中
  • 是的,你可以使用pandas read_csvto_html :)但是如果你需要一些自定义,知道如何在没有熊猫的情况下做它是很好的。或者只是作为编程练习。

0
投票

这应该工作得很好:

from html import HTML
import csv

def to_html(csvfile):
    t=H.table(border='2')
    r = t.tr
    with open(csvfile) as csvfile:
        reader = csv.DictReader(csvfile)
        for column in reader.fieldnames:
            r.td(column)
        for row in reader:
            t.tr
            for col in row.iteritems():
                t.td(col[1])
    return t

并通过将csv文件传递给它来调用该函数。


-1
投票

下面的函数将filename,headers(可选)和delimiter(可选)作为输入,并将csv转换为html表并返回为字符串。如果未提供标头,则假定标头已存在于csv文件中。

Converts csv file contents to HTML formatted table

def csv_to_html_table(fname,headers=None,delimiter=","):
    with open(fname) as f:
        content = f.readlines()
    #reading file content into list
    rows = [x.strip() for x in content]
    table = "<table>"
    #creating HTML header row if header is provided 
    if headers is not None:
        table+= "".join(["<th>"+cell+"</th>" for cell in headers.split(delimiter)])
    else:
        table+= "".join(["<th>"+cell+"</th>" for cell in rows[0].split(delimiter)])
        rows=rows[1:]
    #Converting csv to html row by row
    for row in rows:
        table+= "<tr>" + "".join(["<td>"+cell+"</td>" for cell in row.split(delimiter)]) + "</tr>" + "\n"
    table+="</table><br>"
    return table

在您的情况下,函数调用将如下所示:

filename="Crushers.csv"
myheader='age,week,opp,ACscr,OPPscr,location'
html_table=csv_to_html_table(filename,myheader)
© www.soinside.com 2019 - 2024. All rights reserved.