Skip to content

Instantly share code, notes, and snippets.

@shubhamkumar13
Created October 12, 2020 17:02
Show Gist options
  • Save shubhamkumar13/0c7d7a2a1e9468240e7f4b7c4e891ff5 to your computer and use it in GitHub Desktop.
Save shubhamkumar13/0c7d7a2a1e9468240e7f4b7c4e891ff5 to your computer and use it in GitHub Desktop.
Convert as csv to an html table
module String = struct
include Astring.String
let tail str = with_index_range ~first:1 ~last:(length str) str
end
let create_thead str =
let rec loop acc_lst acc_str str =
match String.head str with
| Some ch when ch = ',' -> loop (acc_str :: acc_lst) "" (String.tail str)
| Some ch ->
loop acc_lst
(String.append acc_str (String.of_char ch))
(String.tail str)
| None -> acc_lst
in
loop [] "" str |> fun str_lst ->
List.map (fun s -> String.append "<th>" @@ String.append s "</th>") str_lst
|> fun str_lst ->
String.concat ~sep:"\n" str_lst |> fun str ->
String.append "<thead>\n<tr>\n" @@ String.append str "\n</tr>\n</thead>"
let create_tbody str_lst =
let create_row_body str =
let rec loop acc_lst acc_str str =
match String.head str with
| Some ch when ch = ',' -> loop (acc_str :: acc_lst) "" (String.tail str)
| Some ch ->
loop acc_lst
(String.append acc_str (String.of_char ch))
(String.tail str)
| None -> acc_lst
in
loop [] "" str |> fun str_lst ->
List.map (fun s -> String.append "<td>" @@ String.append s "</td>") str_lst
|> fun str_lst ->
String.concat ~sep:"\n" str_lst |> fun str ->
String.append "<tr>\n" @@ String.append str "\n</tr>"
in
List.map create_row_body str_lst |> fun str_lst ->
String.concat ~sep:"\n" str_lst |> fun str ->
String.append "\n<tbody>\n" @@ String.append str "\n</tobdy>"
let input () =
let file_channel =
Stdlib.open_in "/home/sk/learnOCaml/csv_to_html_table/example.csv"
in
let rec loop acc =
match input_line file_channel with
| exception End_of_file -> acc
| x -> loop @@ (x :: acc)
in
loop []
|> List.map (fun s -> String.filter (fun x -> x != '\"') s)
|> List.rev
let _ =
input () |> fun lst ->
let column_header = create_thead @@ List.hd lst in
let column_elements = create_tbody @@ List.tl lst in
Printf.printf "%s%s\n" column_header column_elements
(* List.iter (fun s -> Printf.printf "%s" s) lst *)
@shubhamkumar13
Copy link
Author

example csv file that I use

car name,miles/gallon,cylinders,displacement,horsepower,weight,acceleration,model year,origin
"chevrolet chevelle malibu",18,8,307,130,3504,12,70,1
"buick skylark 320",15,8,350,165,3693,11.5,70,1
"plymouth satellite",18,8,318,150,3436,11,70,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment