Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96160
License: OTHER
1
"""This file contains code related to "Think Stats",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2012 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
import csv
9
10
11
def read_csv(filename, constructor):
12
"""Reads a CSV file, returns the header line and a list of objects.
13
14
filename: string filename
15
"""
16
fp = open(filename)
17
reader = csv.reader(fp)
18
19
header = reader.next()
20
names = [s.lower() for s in header]
21
22
objs = [make_object(t, names, constructor) for t in reader]
23
fp.close()
24
25
return objs
26
27
28
def write_csv(filename, header, data):
29
"""Writes a CSV file
30
31
filename: string filename
32
header: list of strings
33
data: list of rows
34
"""
35
fp = open(filename, 'w')
36
writer = csv.writer(fp)
37
writer.writerow(header)
38
39
for t in data:
40
writer.writerow(t)
41
fp.close()
42
43
44
def print_cols(cols):
45
"""Prints the index and first two elements for each column.
46
47
cols: list of columns
48
"""
49
for i, col in enumerate(cols):
50
print i, col[0], col[1]
51
52
53
def make_col_dict(cols, names):
54
"""Selects columns from a dataset and returns a map from name to column.
55
56
cols: list of columns
57
names: list of names
58
"""
59
col_dict = {}
60
for name, col in zip(names, cols):
61
col_dict[name] = col
62
return col_dict
63
64
65
def make_object(row, names, constructor):
66
"""Turns a row of values into an object.
67
68
row: row of values
69
names: list of attribute names
70
constructor: function that makes the objects
71
72
Returns: new object
73
"""
74
obj = constructor()
75
for name, val in zip(names, row):
76
func = constructor.convert.get(name, int)
77
try:
78
val = func(val)
79
except:
80
pass
81
setattr(obj, name, val)
82
obj.clean()
83
return obj
84
85
86