📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This file contains code related to "Think Stats",1by Allen B. Downey, available from greenteapress.com23Copyright 2012 Allen B. Downey4License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html5"""67import csv8910def read_csv(filename, constructor):11"""Reads a CSV file, returns the header line and a list of objects.1213filename: string filename14"""15fp = open(filename)16reader = csv.reader(fp)1718header = reader.next()19names = [s.lower() for s in header]2021objs = [make_object(t, names, constructor) for t in reader]22fp.close()2324return objs252627def write_csv(filename, header, data):28"""Writes a CSV file2930filename: string filename31header: list of strings32data: list of rows33"""34fp = open(filename, 'w')35writer = csv.writer(fp)36writer.writerow(header)3738for t in data:39writer.writerow(t)40fp.close()414243def print_cols(cols):44"""Prints the index and first two elements for each column.4546cols: list of columns47"""48for i, col in enumerate(cols):49print i, col[0], col[1]505152def make_col_dict(cols, names):53"""Selects columns from a dataset and returns a map from name to column.5455cols: list of columns56names: list of names57"""58col_dict = {}59for name, col in zip(names, cols):60col_dict[name] = col61return col_dict626364def make_object(row, names, constructor):65"""Turns a row of values into an object.6667row: row of values68names: list of attribute names69constructor: function that makes the objects7071Returns: new object72"""73obj = constructor()74for name, val in zip(names, row):75func = constructor.convert.get(name, int)76try:77val = func(val)78except:79pass80setattr(obj, name, val)81obj.clean()82return obj83848586