<s> import csv <EOL> from . renderers import StringIO <EOL> def parse_csv ( string ) : <EOL> """<STR_LIT>""" <EOL> if not string . startswith ( '<STR_LIT:U+002C>' ) : <EOL> data = [ ] <EOL> for row in csv . DictReader ( StringIO ( string ) ) : <EOL> for key , val in row . items ( ) : <EOL> try : <EOL> row [ key ] = float ( val ) <EOL> except ValueError : <EOL> pass <EOL> data . append ( row ) <EOL> return [ { <EOL> '<STR_LIT:data>' : data <EOL> } ] <EOL> reader = csv . reader ( StringIO ( string ) ) <EOL> val_cols = None <EOL> val_start = None <EOL> id_cols = None <EOL> for row in reader : <EOL> if row [ <NUM_LIT:0> ] == '<STR_LIT>' and not val_cols : <EOL> val_start = row . count ( '<STR_LIT>' ) <EOL> val_cols = row [ val_start : ] <EOL> col_meta = [ { } for v in val_cols ] <EOL> elif row [ - <NUM_LIT:1> ] != '<STR_LIT>' and val_cols and not id_cols : <EOL> key = row [ <NUM_LIT:0> ] <EOL> for i , meta in enumerate ( row [ val_start : ] ) : <EOL> col_meta [ i ] . update ( ** { key : meta } ) <EOL> elif row [ - <NUM_LIT:1> ] == '<STR_LIT>' and not id_cols : <EOL> id_cols = row [ : row . index ( '<STR_LIT>' ) ] <EOL> meta_index = { } <EOL> meta_i = <NUM_LIT:0> <EOL> datasets = [ ] <EOL> for i , ds1 in enumerate ( col_meta ) : <EOL> if i in meta_index : <EOL> continue <EOL> meta_index [ i ] = meta_i <EOL> meta_i += <NUM_LIT:1> <EOL> datasets . append ( ds1 ) <EOL> if i < len ( col_meta ) : <EOL> for j , ds2 in enumerate ( col_meta [ i + <NUM_LIT:1> : ] ) : <EOL> if ds1 == ds2 : <EOL> meta_index [ i + j + <NUM_LIT:1> ] = i <EOL> for d in datasets : <EOL> d [ '<STR_LIT:data>' ] = [ ] <EOL> elif val_cols and id_cols : <EOL> ids = { <EOL> key : val <EOL> for key , val in zip ( id_cols , row [ : len ( id_cols ) ] ) <EOL> } <EOL> records = { } <EOL> for i , val in enumerate ( row [ len ( id_cols ) : ] ) : <EOL> mi = meta_index [ i ] <EOL> if mi not in records : <EOL> data = ids . copy ( ) <EOL> else : <EOL> data = records [ mi ] <EOL> try : <EOL> val = float ( val ) <EOL> except ValueError : <EOL> pass <EOL> if val != '<STR_LIT>' : <EOL> data [ val_cols [ i ] ] = val <EOL> records [ mi ] = data <EOL> for mi , data in records . items ( ) : <EOL> datasets [ mi ] [ '<STR_LIT:data>' ] . append ( data ) <EOL> return datasets </s>
