使用python创建html页面

时间:2017-05-27 14:40:10

标签: python html csv

嗨我试图读取一个csv文件并将特定数据放入html表并创建一个包含该表的html页面。 我的csv文件有大约110行和5列,分别为“Opposition”,“Winner”,“Margin”,“Ground”和“Year”。列“年份”包含2012年,2013年,2014年,2015年,2016年,2017年的六个级别。我尝试提取“Year = 2012”的数据,并创建一个包含我提取的数据的html表的html页面。 我的csv文件就像;

Opposition,Winner,Margin,Ground,Year
aa,mi,8runs,ab,2012
bb,bb,7runs,ac,2012
cc,cc,2runs,ab,2013
aa,aa,3runs,ac,2014

我需要将2012年作为年份的行,在我的“2012.html”页面中作为表格。 到目前为止,我的代码是:

infile = open("new.csv", "r")
data = []
for line in infile:
    cols = line.split(",")
    Oposition = cols[0]
    Winner = cols[1]
    Margin = cols[2]
    Ground = cols[3]
    Year = cols[4]
    pair = (Oposition, Winner, Margin, Ground, Year)
    data.append(pair)
infile.close()

out1 = open("2012.html", "w")
out1.write("""<!DOCTYPE html>
  <html>
  <head>
  </head>
  <body>
""")
for r in data:
    if r["Year"] == "2012":
        Oposition = r["Oposition"]
        Winner = r["Winner"]
        Margin = r["Margin"]
        Year = r["Year"]
        out1.write("    <p>" + c + " " + str(p) + "</p>\n")
out1.write("  </body>\n")
out1.write("</html>\n")
out1.close()
任何人帮助我。 非常感激。 在2012 html页面里面,我需要一张像这样的表格; sample table

获胜者专栏的饼图

1 个答案:

答案 0 :(得分:0)

我认为你在获得Year =&#34; 2012&#34;使用python进行和创建html表。在代码下方可能会解决您的问题。

   infile = open("new.csv", "r")
data = []
for line in infile:
    cols = line.split(",")
    Oposition = cols[0]
    Winner = cols[1]
    Margin = cols[2]
    Ground = cols[3]
    Year = cols[4]
    pair = (Oposition, Winner, Margin, Ground, Year)
    data.append(pair)
infile.close()

out1 = open("2012.html", "w")
out1.write("""<!DOCTYPE html>
  <html>
  <head>
  </head>
  <body>
  <table border="1"><tr><th>Oposition</th><th>Winner</th><th>Margin</th><th>Ground</th><th>Year</th></tr>

""")
for r in data:
    if ''.join(r[4].split()) == "2012":
        Oposition = r[0]
        Winner = r[1]
        Margin = r[2]
        Ground=r[3]
        Year = r[4]
        out1.write("<tr> <td>" + Oposition+ '</td><td> '+ Winner+'</td><td> '+Margin+'</td><td> '+Ground+' </td><td>'+ Year+ " </td></tr>")

out1.write("</table>  </body>\n")
out1.write("</html>\n")
out1.close()

当您将(Oposition, Winner, Margin, Ground, Year)个变量的值附加到列表r时。访问r["Year"] == "2012"会导致错误,因为r是一个列表,我们可以使用索引而不是名称来获取值。 / p>