Advertisement
Guest User

utils.clj

a guest
Nov 30th, 2011
134
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. (defn -load-tsv
  6.   "Reads a TSV file in and returns a sorted map with the first column's data
  7.  as keys, and for values, hashmaps of the header row's data as keys to the
  8.  other rows' data as values.  A file with a first row of 'Name\tID\tSalary'
  9.  and a second row of 'John\t1\t100' will return a sorted map of {\"John\"
  10.  {\"Name\" \"John\", \"ID\" 1, \"Salary\" 100}}"
  11.   [filename]
  12.   (def tbl-rows (st/split-lines  (slurp (File. filename))))
  13.   (def pat-t (. Pattern compile "\t"))
  14.   (def header (st/split (first tbl-rows) pat-t))
  15.   (defn- read-unknown [s]
  16.     (if (integer? (read-string s)) (read-string s) s))
  17.   (defn- make-data [rw] (zipmap header (map read-unknown (st/split rw pat-t))))
  18.   (apply sorted-map (interleave
  19.                                      (map (fn [rw] (first (st/split rw pat-t))) (rest tbl-rows))
  20.                                      (map make-data (rest tbl-rows)))))
  21. (defn -read-obj
  22.   "Reads a clojure object from a file, ignoring exceptions."
  23.   [fname]
  24.   (try
  25.      (read-string (slurp fname))
  26.   (catch Exception e nil)))
  27.  
  28. (defn -write-obj
  29.   "Writes a clojure object to a file, to be loaded with read-hash ."
  30.   [fname o]
  31.   (binding [*out* (java.io.FileWriter. fname)]
  32.     (prn o)))
  33.  
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement