Last active
December 16, 2015 11:39
-
-
Save mnzk/5428537 to your computer and use it in GitHub Desktop.
instaparse example (CSV parser)
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
(ns example.instaparse | |
(:require [instaparse.core :refer [parser transform]] | |
[hiccup.core :refer [html]])) | |
(def csv-bnf "https://gist.github.com/mnzk/5426024/raw/11de5851adc5b3dd704ec4079c22aa6ff8d131df/csv-bnf-rfc4180.txt") | |
(def csv-parser (parser csv-bnf)) | |
(def data-file "/path/to/data.csv") | |
(def tree (csv-parser (slurp data-file))) | |
(def csv-hiccup-transform | |
(let [take-even #(take-nth 2 %)] | |
(partial transform | |
{:file #(->> (take-even %&) (cons :table) vec) | |
:header #(->> (take-even %&) (cons :tr) vec) | |
:record #(->> (take-even %&) (cons :tr) vec) | |
:name #(vector :th %) | |
:field #(vector :td %) | |
:escaped #(->> (rest %&) drop-last (apply str)) | |
:2DQUOTE (constantly "\"") | |
:non-escaped str | |
:CRLF str | |
:CR (constantly "[CR]") | |
:LF (constantly "[LF]") | |
:COMMA identity | |
:TEXTDATA identity}))) | |
(print (html (csv-hiccup-transform tree))) | |
;;=> <table><tr><td>aa</td><td>bb</td></tr><tr><td>cc</td><td>dd,ee"F"</td></tr><tr><td></td><td>gg[CR][LF]hh</td></tr></table> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment