2017-05-27 48 views
0

嗨im试图读取csv文件并将具体数据放入html表格并创建一个包含该表格的html页面。 我的csv文件有大约110行和5列,分别为“反对”,“赢家”,“边距”,“地面”和“年份”。列“年”包含2012年,2013年,2014年,2015年,2016年,2017年六个级别。我试图提取“年= 2012”的数据并创建一个包含我提取数据的html表格的html页面。 我的csv文件就像;使用python创建html页面

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

究竟是什么问题? – JazZ

+0

给我们一个简短的示例new.csv – Ahmad

+0

即时尝试创建一个名为“2012.html”的html网页,并在该页面中创建一个包含“年= 2012”数据的表格。 – Dush

回答

0

饼图我假设你有在获得年度=“2012” enrtries并使用下面的代码python.Hopefully可能会解决你的问题创建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 .Accessing r["Year"] == "2012"会造成误差r是一个列表,我们可以使用索引,而不是名称获取值。

+0

是它的工作:) – Dush

+0

很高兴它的工作:) –

+0

嗨在同一页内,我试图做一个饼图,显示使用专栏“赢家”的胜利团队。只是无法弄清楚。任何帮助? – Dush