简体   繁体   English

如何从Clojure中的文件读取多个变量?

[英]How to read multiple variables from a file in Clojure?

Coming from OOP, I'm having a bit of trouble adjusting to the immutability of Clojure. 来自OOP,在调整Clojure的不变性时遇到了一些麻烦。

What I want to do is grab some variables from a file, and store each variable and its data to a map. 我想要做的是从文件中获取一些变量,并将每个变量及其数据存储到映射中。

In other words, I want to 'extract' a map from a text file. 换句话说,我想从文本文件中“提取”地图。

As an example, the file would look like this: 例如,文件如下所示:

username: michael
password: foo123
email: barfoo@gmail.com

My question is, how do I convert the above file into a map like this: (?) 我的问题是,如何将上述文件转换成这样的地图:(?)

{:username "michael", :password "foo123", :email "barfoo@gmail.com"}

This is what I had so far, but I have no idea how to get multiple variables: 这是我到目前为止的内容,但是我不知道如何获取多个变量:

(with-open [rdr (reader "/path/to/file.txt")]
  (doseq [line (line-seq rdr)]
    // make map here somehow? ))

Try this: 尝试这个:

(->> (clojure.string/split (slurp "yourfile.txt") #"\n")
     (map #(clojure.string/split % #":"))
     (map (fn [[k v]] [(keyword k) v]))
     (into {}))

slurp function read a file and returns a string of file contents. slurp函数读取文件并返回文件内容的字符串。 It's useful to read text file into a string. 将文本文件读取为字符串很有用。 After that, split the string by \\n , which retrun a sequence of strings. 之后,用\\n分割字符串,重新运行一系列字符串。 Then split each string by : . 然后用:分割每个字符串。

You can check each step in the REPL and see the result of each step, like this: 您可以检查REPL中的每个步骤,并查看每个步骤的结果,如下所示:

user=> (->> (clojure.string/split (slurp "yourfile.txt") #"\n"))
["username: michael" "password: foo123" "email: barfoo@gmail.com"]
user=> (->> (clojure.string/split (slurp "yourfile.txt") #"\n")
            (map #(clojure.string/split % #":\s*")))
(["username" "michael"] ["password" "foo123"] ["email" "barfoo@gmail.com"])
user=> (->> (clojure.string/split (slurp "yourfile.txt") #"\n")
            (map #(clojure.string/split % #":\s*"))
            (map (fn [[k v]] [(keyword k) v])))
([:username "michael"] [:password "foo123"] [:email "barfoo@gmail.com"])
user=> (->> (clojure.string/split (slurp "yourfile.txt") #"\n")
            (map #(clojure.string/split % #":\s*"))
            (map (fn [[k v]] [(keyword k) v]))
            (into {}))
{:username "michael", :password "foo123", :email "barfoo@gmail.com"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM