Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns vc.utils
- (:require [clojure.string :as st])
- (:import (java.util.regex Pattern) (java.io File))
- (:gen-class
- :name "vc.utils.TSVReader"
- :methods [^{:static true} [loadTSV [String] Object
- readObj [String] Object
- writeObj [String Object] String]]))
- (defn- load-tsv
- "Reads a TSV file in and returns a sorted map with the first column's data
- as keys, and for values, hashmaps of the header row's data as keys to the
- other rows' data as values. A file with a first row of 'Name\tID\tSalary'
- and a second row of 'John\t1\t100' will return a sorted map of {\"John\"
- {\"Name\" \"John\", \"ID\" 1, \"Salary\" 100}}"
- [filename]
- (let [tbl-rows (st/split-lines (slurp (File. filename)))
- pat-t (. Pattern compile "\t")
- header (st/split (first tbl-rows) pat-t)]
- (defn- read-unknown [s]
- (if (integer? (read-string s)) (read-string s) s))
- (defn- make-data [rw] (zipmap header (map read-unknown (st/split rw pat-t))))
- (apply sorted-map (interleave
- (map (fn [rw] (first (st/split rw pat-t))) (rest tbl-rows))
- (map make-data (rest tbl-rows))))))
- (defn loadTSV
- "Reads a TSV file in and returns a sorted map with the first column's data
- as keys, and for values, hashmaps of the header row's data as keys to the
- other rows' data as values. A file with a first row of 'Name\tID\tSalary'
- and a second row of 'John\t1\t100' will return a sorted map of {\"John\"
- {\"Name\" \"John\", \"ID\" 1, \"Salary\" 100}}"
- [filename]
- (load-tsv filename))
- (defn- read-obj
- "Reads a clojure object from a file, ignoring exceptions."
- [fname]
- (try
- (read-string (slurp fname))
- (catch Exception e nil)))
- (defn readObj
- "Reads a clojure object from a file, ignoring exceptions."
- [fname]
- (read-obj fname))
- (defn- write-obj
- "Writes a clojure object to a file, to be loaded with read-hash ."
- [fname o]
- (binding [*out* (java.io.FileWriter. fname)]
- (prn o)))
- (defn writeObj
- "Writes a clojure object to a file, to be loaded with read-hash ."
- [fname obj]
- (write-obj fname obj))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement