Advertisement
Guest User

utils.clj

a guest
Nov 30th, 2011
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns vc.utils
  2.   (:require [clojure.string :as st])
  3.   (:import (java.util.regex Pattern) (java.io File))
  4.   (:gen-class
  5.     :name "vc.utils.TSVReader"
  6.     :methods [^{:static true} [loadTSV [String] Object
  7.               readObj [String] Object
  8.               writeObj [String Object] String]]))
  9. (defn- load-tsv
  10.   "Reads a TSV file in and returns a sorted map with the first column's data
  11.  as keys, and for values, hashmaps of the header row's data as keys to the
  12.  other rows' data as values.  A file with a first row of 'Name\tID\tSalary'
  13.  and a second row of 'John\t1\t100' will return a sorted map of {\"John\"
  14.  {\"Name\" \"John\", \"ID\" 1, \"Salary\" 100}}"
  15.   [filename]
  16.   (let [tbl-rows (st/split-lines  (slurp (File. filename)))
  17.         pat-t (. Pattern compile "\t")
  18.         header (st/split (first tbl-rows) pat-t)]
  19.   (defn- read-unknown [s]
  20.     (if (integer? (read-string s)) (read-string s) s))
  21.   (defn- make-data [rw] (zipmap header (map read-unknown (st/split rw pat-t))))
  22.   (apply sorted-map (interleave
  23.                                      (map (fn [rw] (first (st/split rw pat-t))) (rest tbl-rows))
  24.                                      (map make-data (rest tbl-rows))))))
  25. (defn loadTSV
  26.   "Reads a TSV file in and returns a sorted map with the first column's data
  27.  as keys, and for values, hashmaps of the header row's data as keys to the
  28.  other rows' data as values.  A file with a first row of 'Name\tID\tSalary'
  29.  and a second row of 'John\t1\t100' will return a sorted map of {\"John\"
  30.  {\"Name\" \"John\", \"ID\" 1, \"Salary\" 100}}"
  31.   [filename]
  32.   (load-tsv filename))
  33. (defn- read-obj
  34.   "Reads a clojure object from a file, ignoring exceptions."
  35.   [fname]
  36.   (try
  37.      (read-string (slurp fname))
  38.   (catch Exception e nil)))
  39. (defn readObj
  40.   "Reads a clojure object from a file, ignoring exceptions."
  41.   [fname]
  42.   (read-obj fname))
  43. (defn- write-obj
  44.   "Writes a clojure object to a file, to be loaded with read-hash ."
  45.   [fname o]
  46.   (binding [*out* (java.io.FileWriter. fname)]
  47.     (prn o)))
  48. (defn writeObj
  49.   "Writes a clojure object to a file, to be loaded with read-hash ."
  50.   [fname obj]
  51.   (write-obj fname obj))
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement