Created
March 8, 2012 06:30
-
-
Save valvallow/1999187 to your computer and use it in GitHub Desktop.
csv column remapper
This file contains 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
#!/usr/local/bin/gosh | |
(use srfi-1) | |
(use text.csv) | |
(use file.util) | |
(use rfc.json) | |
(use util.list) | |
(use gauche.parseopt) | |
(define (usage) | |
(print "Usage: csvremap [opt ...] <mapping-table-json> <csv-file>") | |
(print " h|help => print this usage") | |
(print " d|delimiter => delimiter (default ,)") | |
(print " t|tsv") | |
(print " json spec => '{csv-column-name:{csv-column-value:substitution, ...}, ...}'") | |
(exit 1)) | |
(define (write-csv csv port :optional (delim #\,)) | |
(let1 writer (make-csv-writer delim) | |
(for-each (pa$ writer port) csv))) | |
(define (csv->list file :optional (delim #\,)) | |
(port->list (make-csv-reader delim) | |
(if file | |
(open-input-file file) | |
(current-input-port)))) | |
(define (file->json file) | |
(parse-json-string | |
(if file | |
(file->string file) | |
(port->string (current-input-port))))) | |
(define (map-csv-columns csv table) | |
(if (or (null? csv) | |
(null? table)) | |
csv | |
(let ((header (car csv)) | |
(csv (cdr csv))) | |
(cons header | |
(map (^[csv-row] | |
(map (^[name val] | |
(let1 table-row (assoc-ref table name) | |
(let1 new-val (and table-row (assoc-ref table-row val)) | |
(or new-val val)))) | |
header csv-row)) | |
csv))))) | |
(define (main args) | |
(let-args (cdr args) | |
((help "h|help" => usage) | |
(delim "d|delimiter=s" ",") | |
(tsv "t|tsv") | |
(else (opt . _) | |
(print "Unknown option : " opt) | |
(usage)) | |
. rest) | |
(when (null? rest) | |
(print "wrong number of arguments. required 1, got 0.") | |
(usage)) | |
(let* ((delim (if tsv #\tab (~ delim 0))) | |
(table (file->json (and (not (null? rest))(car rest)))) | |
(csv (csv->list (and (not (null? (cdr rest))) | |
(cadr rest)) delim))) | |
(write-csv (map-csv-columns csv table) | |
(current-output-port) | |
delim)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment