用Python将CSV转换成HTML表

2024-06-16 13:33:37 发布

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

我正在尝试从.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)

Tags: 文件csvhttpsagehtmlwwwlinelocation
3条回答

首先安装熊猫:

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())

你会得到这样的东西:

&13;
&13;
<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>

这也应该有效:

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文件传递给函数来调用该函数。

在开始打印所需的行之前,输出一些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>")

相关问题 更多 >