1 (* csv.ml - comma separated values parser
3 * $Id: csv.ml,v 1.11 2006-07-19 09:41:58 rich Exp $
6 (* The format of CSV files:
8 * Each field starts with either a double quote char or some other
9 * char. For the some other char case things are simple: just read up
10 * to the next comma (,) which marks the end of the field.
12 * In the case where a field begins with a double quote char the
13 * parsing rules are different. Any double quotes are doubled ("") and
14 * we finish reading when we reach an undoubled quote. eg: "The
15 * following is a quote: "", and that's all" is the CSV equivalent of
16 * the following literal field: The following is a quote: ", and that's
19 * "0 is the quoted form of ASCII NUL.
21 * CSV fields can also contain literal carriage return characters, if
22 * they are quoted, eg: "This field
23 * is split over lines" represents a
24 * single field containing a \n.
26 * Excel will only use the quoting format if a field contains a double
27 * quote or comma, although there's no reason why Excel couldn't always
28 * use the quoted format.
30 * The practical upshot of this is that you can't split a line in a CSV
31 * file just by looking at the commas. You need to parse each field
34 * How we represent CSV files:
36 * We load in the whole CSV file at once, and store it internally as a
37 * 'string list list' type (note that each line in the CSV file can,
38 * and often will, have different lengths). We then provide simple
39 * functions to read the CSV file line-by-line, copy it out, or copy a
40 * subset of it into a matrix.
45 type t = string list list
47 exception Bad_CSV_file of string
49 let rec dropwhile f = function
51 | x :: xs when f x -> dropwhile f xs
55 let rec drop n = function
56 | _ :: l when n > 0 -> drop (n-1) l
59 let rec take n = function
60 | x :: xs when n > 0 -> x :: take (pred n) xs
63 let lines = List.length
66 List.fold_left max 0 (List.map List.length csv)
68 type state_t = StartField
71 | InQuotedFieldAfterQuote
73 let load_rows ?(separator = ',') f chan =
74 let row = ref [] in (* Current row. *)
75 let field = ref [] in (* Current field. *)
76 let state = ref StartField in (* Current state. *)
78 let field_list = List.rev !field in
79 let field_len = List.length field_list in
80 let field_str = String.create field_len in
81 let rec loop i = function
88 row := field_str :: !row;
98 let row_list = List.rev !row in
104 let c = input_char chan in
105 if c != '\r' then ( (* Always ignore \r characters. *)
107 StartField -> (* Expecting quote or other char. *)
109 state := InQuotedField;
111 ) else if c = separator then (* Empty field. *)
113 else if c = '\n' then ( (* Empty field, end of row. *)
117 state := InUnquotedField;
120 | InUnquotedField -> (* Reading chars to end of field. *)
121 if c = separator then (* End of field. *)
123 else if c = '\n' then ( (* End of field and end of row. *)
128 | InQuotedField -> (* Reading chars to end of field. *)
130 state := InQuotedFieldAfterQuote
133 | InQuotedFieldAfterQuote ->
134 if c = '"' then ( (* Doubled quote. *)
135 field := c :: !field;
136 state := InQuotedField
137 ) else if c = '0' then ( (* Quote-0 is ASCII NUL. *)
138 field := '\000' :: !field;
139 state := InQuotedField
140 ) else if c = separator then (* End of field. *)
142 else if c = '\n' then ( (* End of field and end of row. *)
145 ) else ( (* Bad single quote in field. *)
146 field := c :: '"' :: !field;
147 state := InQuotedField
149 ); (* end of match *)
156 (* Any part left to write out? *)
160 ( empty_field (); end_of_row () )
161 | InUnquotedField | InQuotedFieldAfterQuote ->
162 end_of_field (); end_of_row ()
164 raise (Bad_CSV_file "Missing end quote after quoted field.")
167 let load_in ?separator chan =
172 load_rows ?separator f chan;
175 let load ?separator filename =
176 let chan = open_in filename in
177 let csv = load_in ?separator chan in
181 let trim ?(top=true) ?(left=true) ?(right=true) ?(bottom=true) csv =
182 let rec empty_row = function
184 | x :: xs when x <> "" -> false
185 | x :: xs -> empty_row xs
187 let csv = if top then dropwhile empty_row csv else csv in
191 let row = List.rev row in
192 let row = dropwhile ((=) "") row in
193 let row = List.rev row in
198 let csv = List.rev csv in
199 let csv = dropwhile empty_row csv in
200 let csv = List.rev csv in
204 let empty_left_cell =
205 function [] -> true | x :: xs when x = "" -> true | _ -> false in
207 List.fold_left (fun a row -> a && empty_left_cell row) true in
208 let remove_left_col =
209 List.map (function [] -> [] | x :: xs -> xs) in
211 if empty_left_col csv then (
212 let csv = remove_left_col csv in
217 let csv = if left then loop csv else csv in
222 let columns = columns csv in
225 let n = List.length row in
226 let row = List.rev row in
227 let rec loop acc = function
229 | i -> "" :: loop acc (i-1)
231 let row = loop row (columns - n) in
236 let columns = columns csv in
237 List.for_all (fun row -> List.length row = columns) csv
239 let rec set_columns cols = function
242 let rec loop i cells =
245 | [] -> "" :: loop (succ i) []
246 | c :: cs -> c :: loop (succ i) cs
250 loop 0 r :: set_columns cols rs
252 let rec set_rows rows csv =
255 | [] -> [] :: set_rows (pred rows) []
256 | r :: rs -> r :: set_rows (pred rows) rs
260 let set_size rows cols csv =
261 set_columns cols (set_rows rows csv)
263 let sub r c rows cols csv =
264 let csv = drop r csv in
265 let csv = List.map (drop c) csv in
266 let csv = set_rows rows csv in
267 let csv = set_columns cols csv in
270 (* Compare two rows for semantic equality - ignoring any blank cells
271 * at the end of each row.
273 let rec compare_row (row1 : string list) row2 =
274 match row1, row2 with
276 | x :: xs, y :: ys ->
277 let c = compare x y in
278 if c <> 0 then c else compare_row xs ys
288 (* Semantic equality for CSV files. *)
289 let rec compare (csv1 : t) csv2 =
290 match csv1, csv2 with
292 | x :: xs, y :: ys ->
293 let c = compare_row x y in
294 if c <> 0 then c else compare xs ys
296 let c = compare_row x [] in
297 if c <> 0 then c else compare xs []
299 let c = compare_row [] y in
300 if c <> 0 then c else compare [] ys
303 Array.of_list (List.map Array.of_list csv)
306 List.map Array.to_list (Array.to_list csv)
308 let associate header data =
309 let nr_cols = List.length header in
310 let rec trunc = function
312 | n, [] -> "" :: trunc (n-1, [])
313 | n, (x :: xs) -> x :: trunc (n-1, xs)
317 let row = trunc (nr_cols, row) in
318 List.combine header row
321 let save_out ?(separator = ',') chan csv =
322 (* Quote a single CSV field. *)
323 let quote_field field =
324 if String.contains field separator ||
325 String.contains field '\"' ||
326 String.contains field '\n'
328 let buffer = Buffer.create 100 in
329 Buffer.add_char buffer '\"';
330 for i = 0 to (String.length field) - 1 do
332 '\"' -> Buffer.add_string buffer "\"\""
333 | c -> Buffer.add_char buffer c
335 Buffer.add_char buffer '\"';
336 Buffer.contents buffer
342 let separator = String.make 1 separator in
343 List.iter (fun line ->
344 output_string chan (String.concat separator
345 (List.map quote_field line));
346 output_char chan '\n') csv
348 let print ?separator csv =
349 save_out ?separator stdout csv; flush stdout
351 let save ?separator file csv =
352 let chan = open_out file in
353 save_out ?separator chan csv;
356 let save_out_readable chan csv =
357 (* Escape all the strings in the CSV file first. *)
358 (* XXX Why are we doing this? I commented it out anyway.
359 let csv = List.map (List.map String.escaped) csv in
362 (* Find the width of each column. *)
364 (* Don't consider rows with only a single element - typically
367 let csv = List.filter (function [_] -> false | _ -> true) csv in
369 (* Square the CSV file - makes the next step simpler to implement. *)
370 let csv = square csv in
375 let lengths_row1 = List.map String.length row1 in
376 let lengths_rest = List.map (List.map String.length) rest in
379 try List.combine r1 r2
381 Invalid_argument "List.combine" ->
382 failwith (sprintf "Csv.save_out_readable: internal error: length r1 = %d, length r2 = %d" (List.length r1) (List.length r2)) in
383 List.map (fun ((a : int), (b : int)) -> max a b) rp
385 List.fold_left max2rows lengths_row1 lengths_rest in
387 (* Print out each cell at the correct width. *)
388 let rec repeat f = function
390 | i -> f (); repeat f (i-1)
394 | [cell] -> (* Single column. *)
395 output_string chan cell;
396 output_char chan '\n'
397 | row -> (* Other. *)
398 (* Pair up each cell with its max width. *)
400 let rec loop = function
402 | (_, []) -> failwith "Csv.save_out_readable: internal error"
403 | (cell :: cells, width :: widths) ->
404 (cell, width) :: loop (cells, widths)
406 loop (row, widths) in
409 output_string chan cell;
410 let n = String.length cell in
411 repeat (fun () -> output_char chan ' ') (width - n + 1)
413 output_char chan '\n'
416 let print_readable = save_out_readable stdout