【发布时间】:2020-09-20 11:22:35
【问题描述】:
我在 clojure 中遇到了一个小问题。我是这个编程环境的新手,需要一点帮助。我有一个这种格式的文本文件:
1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533
我想解析文件中的每一行,并希望以这种方式将数据存储在 hashmap 中:
{ 1 : [John Smith, 123 here street, 456-4567], 2 : ... }
这是我到目前为止的代码,但我还没有成功。
(defn readcustfile[]
(def cust-file (clojure.string/split-lines (slurp "cust.txt")))
(doseq [line cust-file]
(def cust-id (nth (clojure.string/split line #"\|") 0))
(def cust-name (str (nth (clojure.string/split line #"\|") 1)))
(def cust-add (str (nth (clojure.string/split line #"\|") 2)))
(def cust-phone (str (nth (clojure.string/split line #"\|") 3)))
(def cust-data (str cust-name "," cust-add "," cust-phone))
(def cust (map (fn [[id name add phone]]
(list (Integer/parseInt cust-id)
(hash-map :name cust-name
:add cust-add
:phone cust-phone))
)
)
(readcustfile)
【问题讨论】:
-
def在顶层之外通常是禁止的。请改用let。此外,仅通过分隔符拆分来读取 CSV 可能很危险 - 通常最好使用库进行正确解析(例如,那些库可以处理引用/转义)
标签: functional-programming clojure