Created
October 12, 2020 17:02
-
-
Save shubhamkumar13/0c7d7a2a1e9468240e7f4b7c4e891ff5 to your computer and use it in GitHub Desktop.
Convert as csv to an html table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 *) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example csv file that I use