从Clojure中的DataBase打印表

时间:2013-02-22 18:34:18

标签: clojure

我的目标是将表格打印得很近,每个列之间都有均匀的空格。

(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)
)

我尝试过使用Tab但是这是我得到的:

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     |

是否有更好的对齐打印的建议?

4 个答案:

答案 0 :(得分: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 :(得分:2)

这可能会有所帮助:

http://clojuredocs.org/clojure_core/clojure.pprint/print-table

Alpha - 可能会发生变化。 在文本表中打印一组地图。打印表格标题 ks,然后是每行的输出行,对应于键 在ks。如果未指定ks,请使用行中第一项的键。

答案 2 :(得分: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|

答案 3 :(得分:0)

我习惯print-tablewith-out-str

user=> (def res [{:P_Id 1 :LastName "Darmon" :FirstName "Gilad"} {:P_Id 2 :LastName "SM" :FirstName "Shiran"}])
#'user/res
user=> (printf "res=%s" (with-out-str (clojure.pprint/print-table res)))
res=
| :P_Id | :LastName | :FirstName |
|-------+-----------+------------|
|     1 |    Darmon |      Gilad |
|     2 |        SM |     Shiran |
nil