Solution to HW16: HTML Lists and Tables:
#-----------------------
def loadCSVFile(filename):
# Loads CSV from file, splits into list of lists, converts number columns to ints/floats
# Returns list of lists
#Load file, strip() off trailing newlines, split to lines
f = open(filename, "r")
lines = f.read().strip().split("\n")
f.close()
# Split again to get list of lists, or a table
table = []
for line in lines:
row = line.split(",")
table += [row]
# Numbers not needed for this assignment, but this is a way you could do it:
for row in table[1:]: # Don't convert header
try:
row[1] = float(row[1]) # wage
row[2] = int(row[2]) #start date
row[3] = int(row[3]) #end date
except:
print("ERROR: In row: {}, failed to int()/float() columns 1 2 or 3".format(row))
# NOTE: will keep going on error, so numbers may not be fully converted
return table
#-----------------------
def makeHTMLList(words):
# words is list of strings
s = "<ol>\n"
for word in words:
s += "<li>{}</li>\n".format(word) # \n is optional here, makes it more legible
s += "</ol>"
return s
#-----------------------
def makeHTMLRow(row):
# row is list of elements (can be string or number)
rowstring = "<tr>"
for element in row:
rowstring += "<td>{}</td>".format(element)
rowstring += "</tr>"
return rowstring
def makeHTMLTable(LofL):
# LofL is list of lists of elements
tabstring = '<table border="1">\n'
for row in LofL:
tabstring += makeHTMLRow(row) + "\n"
tabstring += "</table>"
return tabstring
#-----------------------
# Here's how we can use the above functions to generate a webpage:
csvTable = loadCSVFile("files/name_and_wage_first10.txt")
table_html = makeHTMLTable(csvTable)
f = open("files/out_table.html","w")
f.write(table_html)
f.close()
#-----------------------
# Here's a helper function that you may find useful when working with html
# We can use it to express some things more compactly, like so:
def inTags(tagname, content):
return "<{}> {} </{}>".format(tagname, content, tagname)
def makeHTMLList2(words):
items = ""
for word in words:
items += inTags("li", word)
return inTags("ol", items)