CSV to HTML translation: Difference between revisions

added ocaml
m (tidy up)
(added ocaml)
Line 18:
For extra credit, ''optionally'' allow special formatting for the
first row of the table as if it is the tables header row.
 
=={{header|OCaml}}==
 
<lang ocaml>let csv_data = "\
Character,Speach
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; \
he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"
 
(* some utility functions *)
 
let string_of_char = String.make 1 ;;
 
let string_of_string_list sl =
List.fold_left (fun s cat -> s ^ cat) "" sl
 
let char_list_of_string str =
let lst = ref [] in
String.iter (fun c -> lst := c :: !lst) str;
(List.rev !lst)
 
(** escape chars that need to be escaped *)
let escape str =
let chars = char_list_of_string str in
let rec aux acc = function
| [] -> (List.rev acc)
| c :: tl ->
match c with
| 'A'..'Z'
| 'a'..'z'
| '0'..'9'
| ' ' | ';' | '!' | '?' ->
aux ((string_of_char c)::acc) tl
| c ->
let esc_char = (Printf.sprintf "&#%04d;" (Char.code c)) in
aux (esc_char::acc) tl
in
string_of_string_list (aux [] chars)
 
(* now the main part *)
 
let html_table_of_csv_data ~csv_data:s =
let len = String.length s in
let rec aux acc_line acc i j =
if i = len then List.rev (acc_line::acc) else
match csv_data.[i] with
| ',' ->
let sub = String.sub s (j+1) (i - j - 1) in
aux (sub::acc_line) acc (succ i) (succ i)
| '\n' ->
let sub = String.sub s j (i - j) in
let acc_line = List.rev (escape sub::acc_line) in
aux [] (acc_line::acc) (succ i) i
| _ ->
aux acc_line acc (succ i) j
in
aux [] [] 0 (-1)
 
let print_table segments =
print_string "<table>\n";
List.iter (fun line ->
print_string "<tr>\n";
List.iter (Printf.printf " <td>%s</td>") line;
print_string "\n</tr>\n";
) segments;
print_string "</table>\n";
;;
 
let () =
let segments = html_table_of_csv_data ~csv_data in
print_table segments</lang>
 
Sample html output:
 
<lang html><table>
<tr>
<td>Character</td> <td>Speach</td>
</tr>
<tr>
<td>The multitude</td> <td>The messiah! Show us the messiah!</td>
</tr>
<tr>
<td>Brians mother</td> <td>&#0060;angry&#0062;Now you listen here! He&#0039;s not the messiah; he&#0039;s a very naughty boy! Now go away!&#0060;&#0047;angry&#0062;</td>
</tr>
<tr>
<td>The multitude</td> <td>Who are you?</td>
</tr>
<tr>
<td>Brians mother</td> <td>I&#0039;m his mother; that&#0039;s who!</td>
</tr>
<tr>
<td>The multitude</td>
</tr>
</table></lang>
 
=={{header|Python}}==