簡體   English   中英

在 Python 中將 CSV 轉換為 HTML 表格

[英]Converting CSV to HTML Table in 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)

首先安裝熊貓:

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>

首先,安裝熊貓:

pip install pandas

然后,

import pandas as pd         
a = pd.read_csv("Crushers.csv") 
# to save as html file 
# named as "Table" 
a.to_html("Table.htm") 
# assign it to a  
# variable (string) 
html_file = a.to_html()

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

首先是一些進口:

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構建字典

  • read_csvhtml_table兩個函數都是通用的,因此它們可以處理任何數據,列名沒有“硬編碼”到它們中

  • 是的,你可以使用熊貓read_csvto_html代替:)不過這是好事,知道如何做沒有的情況下,你需要一些定制大熊貓。 或者只是作為一個編程練習。

這也應該有效:

from html import HTML
import csv

def to_html(csvfile):
    H = HTML()
    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 文件傳遞​​給它來調用該函數。

下面的函數將文件名、標題(可選)和分隔符(可選)作為輸入,並將 csv 轉換為 html 表並作為字符串返回。 如果未提供標頭,則假定標頭已存在於 csv 文件中。

將 csv 文件內容轉換為 HTML 格式的表格

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

在您的情況下,函數調用將如下所示,但這不會過濾掉 csv 中的條目,而是直接將整個 csv 文件轉換為 HTML 表。

filename="Crushers.csv"
myheader='age,week,opp,ACscr,OPPscr,location'
html_table=csv_to_html_table(filename,myheader)

注意:要過濾掉具有特定值的條目,請在 for 循環中添加條件語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM