如何从文本文件中读取字符串并转换为clojure中的地图?

时间:2014-12-01 03:31:25

标签: clojure seesaw

我正在尝试使用Clojure - Seesaw从文件中读取并将字符串转换为映射(变量),以便我可以使用它们打印到GUI。以下是我目前的代码:

(ns store.core
(:gen-class)
(:require [seesaw.core :as seesaw]))

(defn -main
  [& args]
  (seesaw/show!

   (spit "amovies.txt" "")
   ;(spit "amovies.txt" (pr-str [{:id 1 :qty 4 :name "movie1" :price 3.50}
   ;                             {:id 2 :qty 5 :name "movie2" :price 3.00}]) :append true)

   (spit "amovies.txt" "movie: Movie_Name\nprice: 5\nid: 1\nquantity: 2" :append true)

   (print (read-string (slurp "amovies.txt")))

   (with-open [rdr (reade "amovies.txt")]
     (doseq [line (line-seq rdr)]
       (println-str line)))

我很难搞清楚如何逐行读取amovies.txt中的字符串,然后用它创建一个映射。期望的输出应该是这样的 电影:Movie_Name 价格:5 id:1 数量:2

但在某种程度上,如果我要说:电影,它会引用电影的名称。

有人可以帮忙吗?感谢所有帮助!

1 个答案:

答案 0 :(得分:2)

1

(def movies-as-map
  (let [lines (with-open [rdr (reade "amovies.txt")]
                (line-seq rdr))]
    (binding [*read-eval* false]
      (map read-string lines))))

2

user> (def movie
        (binding [*read-eval* false]
          (read-string 
           "{:id 1 :qty 4 :name \"movie1\" :price 3.50}")))

#'user/movie
user> (keys movie)
(:id :qty :name :price)

将使用此

(spit "amovies.txt" 
      (pr-str [{:id 1 :qty 4 :name "movie1" :price 3.50}
               {:id 2 :qty 5 :name "movie2" :price 3.00}]) 
      :append true)

但不是这个

(spit "amovies.txt" 
      "movie: Movie_Name\nprice: 5\nid: 1\nquantity: 2"
      :append true)

docs:https://clojure.github.io/clojure/branch-master/clojure.core-api.html#clojure.core/read-string

错误的args传递给show!

看起来你向跷跷板/表演传递了大量的论据!

文档说明

  

用法:(显示!目标)

     

显示框架,对话框或小部件。

     

如果target是模态对话框,则调用将阻止并显示!将   返回对话框的结果。请参阅(seesaw.core / return-from-dialog)。

     

返回其输入。