2013-02-22 25 views
1

我的目标是将每张表格之间的间距均匀地打印出来。从Clojure中的DataBase打印表格

(defn PrintTable [tableName] 
    "prints table in clear format" 
    (let [tableRef (get (deref dataBase) tableName) ; get refrence for table 
     keyList (keys @tableRef)] ; get key list of table 
    (doseq [tableKeys (range (count keyList))] ; print the keys of the table 
     (let [key (nth (keys @tableRef) tableKeys)] 
     (print key "\t|")) 
    ) 
    (println) 
    (doseq [rows (range (count @(tableRef (nth (keys @tableRef) 0))))] ; print for each rows all the values 
     (doseq [cols (range (count keyList))] 
     (let [key (nth (keys @tableRef) cols)] 
      (print (@(tableRef key) rows) "\t|") 
     ) 
    ) 
     (println) 
    ) 
) 
    (println) 
) 

我一直在使用标签试图然而,这是出落得我得到:

P_Id |LastName |FirstName |Address |City | 
1 |Darmon  |Gilad |ishayahu |Haifa | 
2 |SM  |Shiran  |erez |RamatIshay  | 

D_Id |Name |OwnerLastName |OwnerFirstName  | 
a |Bono |Darmon  |Gilad | 
b |Bony |SM  |Shiran  | 

任何建议,为一个更好的和一致的打印?

+0

参见http://clojuredocs.org/clojure_core/clojure.pprint/print-table。 – 2013-02-22 19:49:53

回答

3

使用format做出的cols排队:

user> (println (format "%20s %20s %20s\n%20s %20s %20s" 
       "short" "medium" "reallylong" 
       "reallylong" "medium" "short")) 

       short    medium   reallylong 
      reallylong    medium    short 
nil 
user> 

或留下%-20s

user> (println (format "%-20s %-20s %-20s\n%-20s %-20s %-20s" 
         "short" "medium" "reallylong" 
         "reallylong" "medium" "short")) 

short    medium    reallylong 
reallylong   medium    short 
nil 
user> 
+1

[格式化选项链接](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html) – 2013-02-22 18:53:20

+0

格式“%-20s”正是我所需要的 – Gilad 2013-02-22 19:12:35

1
(defn print-table [res] 
    (let [headers (map name (keys (first res))) 
     table (concat [headers] (map vals res)) 
     trans-table (apply map vector table) 
     cols-width (map #(apply max (map (comp count str) %)) 
         trans-table)] 
    (doseq [row table] 
     (println 
     (apply format 
       (str "|" (apply str (str/join "|" (map #(str "%-" % "s") 
                cols-width))) 
        "|") 
       row))))) 

(print-table res) 
=> |P_Id|LastName|FirstName|Address |City  | 
    |1 |Darmon |Gilad |ishayahu|Haifa  | 
    |2 |SM  |Shiran |erez |RamatIshay|