In [ ]:
! head -5 ice-cream.csv
In [ ]:
"""The simplest data reader."""
for line in open('ice-cream.csv'):
row = line.split(',')
print(row)
In [ ]:
def read_data(path):
"""Reads comma separated data from path."""
infile = open(path)
infile.readline() # discard headers
for line in infile:
line = line.strip()
row = line.split(',')
print(row)
read_data('ice-cream.csv')
In [ ]:
'1011' / 10
In [ ]:
row = ['1011', 'f', 't']
assert row[1] in 'mf' and row[2] in 'ps'
In [ ]:
line = '"damon, matt", m, p'
line.split(',')
In [ ]:
import csv
def read_data(path):
"""Reads comma separated data from path."""
with open(path) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
assert row['gender'] in 'mf'
assert row['preference'] in 'ps'
print(row['gender'], row['preference'])
read_data('ice-cream.csv')
In [ ]:
counts = {
'm':
{'s': 8,
'p': 12},
'f':
{'s': 16,
'p': 4}
}
In [ ]:
counts['f']
In [ ]:
counts['f']['p']
In [ ]:
import csv
from collections import defaultdict
def ice_cream_counts(path):
"""Returns gender/preference counts from csv in path."""
counts = {'m': defaultdict(int), 'f': defaultdict(int)}
with open(path) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
counts[row['gender']][row['preference']] += 1
return counts
counts = ice_cream_counts('ice-cream.csv')
print(counts)
In [ ]:
def write_html(counts):
flavors = {'p': 'pistachio', 's': 'strawberry'}
heading = """<!DOCTYPE html>
<html><head><title>Ice Cream Preferences</title></head><body>
<table border="1">
<tr> <th>preference</th> <th>female</th> <th>male</th> </tr>"""
table_row = '<tr> <td>{}</td> <td>{}</td> <td>{}</td> </tr>'
print(heading)
for f, flavor in flavors.items():
print(table_row.format(flavor, counts['f'][f], counts['m'][f]))
print('</table></body></html>')
counts = ice_cream_counts('ice-cream.csv')
write_html(counts)
In [ ]: