1 (* csv.ml - comma separated values parser
3 * $Id: csv.ml,v 1.6 2005-08-13 10:10:31 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.
43 type t = string list list
45 exception Bad_CSV_file of string
47 let rec dropwhile f = function
49 | x :: xs when f x -> dropwhile f xs
52 let lines = List.length
55 List.fold_left max 0 (List.map List.length csv)
57 type state_t = StartField
60 | InQuotedFieldAfterQuote
62 let load_rows ?(separator = ',') f chan =
63 let row = ref [] in (* Current row. *)
64 let field = ref [] in (* Current field. *)
65 let state = ref StartField in (* Current state. *)
67 let field_list = List.rev !field in
68 let field_len = List.length field_list in
69 let field_str = String.create field_len in
70 let rec loop i = function
77 row := field_str :: !row;
87 let row_list = List.rev !row in
93 let c = input_char chan in
94 if c != '\r' then ( (* Always ignore \r characters. *)
96 StartField -> (* Expecting quote or other char. *)
98 state := InQuotedField;
100 ) else if c = separator then (* Empty field. *)
102 else if c = '\n' then ( (* Empty field, end of row. *)
106 state := InUnquotedField;
109 | InUnquotedField -> (* Reading chars to end of field. *)
110 if c = separator then (* End of field. *)
112 else if c = '\n' then ( (* End of field and end of row. *)
117 | InQuotedField -> (* Reading chars to end of field. *)
119 state := InQuotedFieldAfterQuote
122 | InQuotedFieldAfterQuote ->
123 if c = '"' then ( (* Doubled quote. *)
124 field := c :: !field;
125 state := InQuotedField
126 ) else if c = '0' then ( (* Quote-0 is ASCII NUL. *)
127 field := '\000' :: !field;
128 state := InQuotedField
129 ) else if c = separator then (* End of field. *)
131 else if c = '\n' then ( (* End of field and end of row. *)
134 ) else ( (* Bad single quote in field. *)
135 field := c :: '"' :: !field;
136 state := InQuotedField
138 ); (* end of match *)
145 (* Any part left to write out? *)
149 ( empty_field (); end_of_row () )
150 | InUnquotedField | InQuotedFieldAfterQuote ->
151 end_of_field (); end_of_row ()
153 raise (Bad_CSV_file "Missing end quote after quoted field.")
156 let load_in ?separator chan =
161 load_rows ?separator f chan;
164 let load ?separator filename =
165 let chan = open_in filename in
166 let csv = load_in ?separator chan in
170 let trim ?(top=true) ?(left=true) ?(right=true) ?(bottom=true) csv =
171 let rec empty_row = function
173 | x :: xs when x <> "" -> false
174 | x :: xs -> empty_row xs
176 let csv = if top then dropwhile empty_row csv else csv in
180 let row = List.rev row in
181 let row = dropwhile ((=) "") row in
182 let row = List.rev row in
187 let csv = List.rev csv in
188 let csv = dropwhile empty_row csv in
189 let csv = List.rev csv in
193 let empty_left_cell =
194 function [] -> true | x :: xs when x = "" -> true | _ -> false in
196 List.fold_left (fun a row -> a && empty_left_cell row) true in
197 let remove_left_col =
198 List.map (function [] -> [] | x :: xs -> xs) in
200 if empty_left_col csv then (
201 let csv = remove_left_col csv in
206 let csv = if left then loop csv else csv in
211 let columns = columns csv in
214 let n = List.length row in
215 let row = List.rev row in
216 let rec loop acc = function
218 | i -> "" :: loop acc (i-1)
220 let row = loop row (columns - n) in
224 let associate header data =
225 let nr_cols = List.length header in
226 let rec trunc = function
228 | n, [] -> "" :: trunc (n-1, [])
229 | n, (x :: xs) -> x :: trunc (n-1, xs)
233 let row = trunc (nr_cols, row) in
234 List.combine header row
237 let save_out ?(separator = ',') chan csv =
238 (* Quote a single CSV field. *)
239 let quote_field field =
240 if String.contains field separator ||
241 String.contains field '\"' ||
242 String.contains field '\n'
244 let buffer = Buffer.create 100 in
245 Buffer.add_char buffer '\"';
246 for i = 0 to (String.length field) - 1 do
248 '\"' -> Buffer.add_string buffer "\"\""
249 | c -> Buffer.add_char buffer c
251 Buffer.add_char buffer '\"';
252 Buffer.contents buffer
258 let separator = String.make 1 separator in
259 List.iter (fun line ->
260 output_string chan (String.concat separator
261 (List.map quote_field line));
262 output_char chan '\n') csv
264 let print ?separator csv =
265 save_out ?separator stdout csv; flush stdout
267 let save ?separator file csv =
268 let chan = open_out file in
269 save_out ?separator chan csv;
272 let save_out_readable chan csv =
273 (* Escape all the strings in the CSV file first. *)
274 let csv = List.map (List.map String.escaped) csv in
276 let csv = square csv in
278 (* Find the width of each column. *)
283 let n = List.length r in
284 let lengths = List.map (List.map String.length) csv in
286 let rp = List.combine r1 r2 in
287 List.map (fun ((a : int), (b : int)) -> max a b) rp
289 let rec repeat x = function
291 | i -> x :: repeat x (i-1)
293 List.fold_left max2rows (repeat 0 n) lengths in
295 (* Print out each cell at the correct width. *)
296 let rec repeat f = function
298 | i -> f (); repeat f (i-1)
302 let row = List.combine widths row in
305 output_string chan cell;
306 let n = String.length cell in
307 repeat (fun () -> output_char chan ' ') (width - n + 1)
309 output_char chan '\n'
312 let print_readable = save_out_readable stdout