comparison dml-cla/python/csvutils.py @ 0:718306e29690 tip

commiting public release
author Daniel Wolff
date Tue, 09 Feb 2016 21:05:06 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:718306e29690
1 # Part of DML (Digital Music Laboratory)
2 # Copyright 2014-2015 Samer Abdallah, University College London
3
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
18 # -*- coding: utf-8 -*-
19 __author__="samer"
20
21 import csv
22 from warnings import warn
23
24 import sys
25 import time
26 def print_status(msg): sys.stderr.write(msg+'\n')
27
28 # call function for each row of a CSV that has ncols columns.
29 # A warning is printed if any rows have the wrong number of columns.
30 #
31 # csv_for_each : string, integer, (list(string) -> void) -> void
32 def csv_for_each(filename,ncols,f):
33 badcount=0
34 with open(filename,'rb') as csvfile:
35 contents=csv.reader(csvfile, delimiter=',',quotechar='"')
36 for row in contents:
37 if len(row)==ncols: f(row)
38 else: badcount += 1
39 # if badcount>0: warn("Ignoring %d malformed rows in CSV file %s" % (badcount,filename))
40
41 # map f over list of rows from CSV to list of values
42 #
43 # csv_map_rows : string, integer, (list(string) -> A) -> list(A)
44 def csv_map_rows(filename,ncols,f):
45 good=[]
46 def append_row(row): good.append(f(row))
47 csv_for_each(filename,ncols,append_row)
48 return good
49
50 def id(x): return x
51
52
53 # returns selected columns of CSV, one list per column
54 #
55 # csv_columns : string, integer, list(integer) -> list(list(string))
56 def csv_columns(filename,ncols,columns):
57 def getter(i): return lambda r:r[i]
58 return csv_map_columns(filename,ncols,map(getter,columns))
59
60 # returns selected columns of CSV, one list per column, with
61 # a function supplied for converting one row of strings to a row of data
62 #
63 # csv_map_columns : string, integer, list(list(string)->A) -> list(list(A))
64 def csv_map_columns(filename,ncols,sels):
65 ii=range(0,len(sels))
66 data=[[] for i in ii]
67 def append_columns(row):
68 for i in ii: data[i].append(sels[i](row))
69 csv_for_each(filename,ncols,append_columns)
70
71 return data