[英]read csv file into python dictionary and create html tables
我是python的初學者,我試圖將csv文件讀入python字典以生成html表。 我的文件中有30列,我想將csv文件中的前4列作為html表中的列,然后將另一個html表中的接下來6列中的依此類推。等等。
oposition mat won lost total overs
aa 5 3 2 400 20
bb 4 2 2 300 20
cc 4 3 1 100 19
我試圖獲取數據為:
<table>
<tr><td>aa</td> <td>5</td> <td>3</td> <td>2</td></tr>
<tr><td>bb</td> <td>4</td> <td>2</td> <td>2</td></tr>
<tr><td>cc</td> <td>4</td> <td>3</td> <td>1</td></tr>
</table>
到目前為止,我的代碼是;
infile = open("minew.csv", "r")
mydict = {}
for line in infile:
words = line.split(",")
oposition = words[0]
mat = words[1]
won = words[2]
lost = words[3]
mydict[oposition] = oposition
mydict[mat] = int(mat)
mydict[won] = int(won)
mydict[lost] = int(lost)
print("<table>")
for o,m,w,l in mydict.keys():
print("<tr><td>{op}</td> <td>{mt}</td> <td>{wi}</td> <td>{lo}</td>
</tr>".format(
op = mydict[oposition],
mt = mydict[mat]
wi = mydict[won]
lo = mydict[lost]))
print("</table>")
我無法使我的代碼正常工作。 請任何人幫我。 非常感激
不要重新發明輪子,請使用現有的csv軟件包 :
import csv
with open('minew.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
for row in reader:
print('<tr>')
for fn in reader.fieldnames:
print('<td>{}</td>'.format(row[fn]))
print('</tr>')
我不清楚在輸入文件中的列之間只有一個字符,例如制表符('\\ t`),在這種情況下,我認為csv模塊可能不適用。 這是另一種方法。
print ('<table>')
with open('minew.csv') as minew:
first = True
for line in minew.readlines():
if first:
first = False
else:
values = line.split()
print ('<tr>', end='')
for value in values:
print ('<td>%s</td>' % value, end='')
print ('</tr>')
print ('</table>')
我認為這與您的代碼之間的主要區別在於,我使用split()
而不是split(',')
因為各列之間存在空格。
這是輸出。
<table>
<tr><td>aa</td><td>5</td><td>3</td><td>2</td></tr>
<tr><td>bb</td><td>4</td><td>2</td><td>2</td></tr>
<tr><td>cc</td><td>4</td><td>3</td><td>1</td></tr>
</table>
我認為您應該了解以下幾點:
1,打開csv文件時,必須使用next()
跳過標題
2,無需創建新的dict來做到這一點,並牢記python dict不排序。
3,只需在第一個循環中使用該元素,因為您已經捕獲了它們。
4,關閉文件后操作始終是一個好習慣。
假設您有csv檔案:
oposition mat won lost total overs
aa 5 3 2 400 20
bb 4 2 2 300 20
cc 4 3 1 100 19
根據您的邏輯,代碼如下:
infile = open("minew.csv", "r")
next(infile)
print("<table>")
for line in infile:
words = line.strip().split()
oposition = words[0]
mat = words[1]
won = words[2]
lost = words[3]
print("<tr><td>{op}</td> <td>{mt}</td> <td>{wi}</td> <td>{lo}</td></tr>".format(op = oposition,mt = mat,wi = won,lo = lost))
print("</table>")
infile.close()
輸出:
<table>
<tr><td>aa</td> <td>5</td> <td>3</td> <td>2</td></tr>
<tr><td>bb</td> <td>4</td> <td>2</td> <td>2</td></tr>
<tr><td>cc</td> <td>4</td> <td>3</td> <td>1</td></tr>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.