将列表向量转换为向量向量

No *_*ame 1 list vector clojure

我在 .txt 文件中有以下数据:

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
Run Code Online (Sandbox Code Playgroud)

我获取数据并使用以下代码将其转换为向量:

(def custContents (slurp "cust.txt"))
(def custVector (clojure.string/split custContents #"\||\n"))
(def testing (into [] (partition 4 custVector )))
Run Code Online (Sandbox Code Playgroud)

这给了我以下向量:

[(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)]
Run Code Online (Sandbox Code Playgroud)

我想将其转换为这样的向量向量:

[[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]]
Run Code Online (Sandbox Code Playgroud)

Ala*_*son 5

我的做法略有不同,所以你先把它分成几行,然后处理每一行。它还使正则表达式更简单:

(ns tst.demo.core
  (:require
    [clojure.string :as str] ))

(def data
"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")

  (let [lines       (str/split-lines data)
        line-vecs-1 (mapv #(str/split % #"\|" ) lines)
        line-vecs-2 (mapv #(str/split % #"[|]") lines)]
    ...)
Run Code Online (Sandbox Code Playgroud)

结果:

lines => ["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"]

line-vecs-1 => 
   [["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"]]

line-vecs-2 => 
   [["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"]]
Run Code Online (Sandbox Code Playgroud)

请注意,有两种方法可以执行正则表达式。 line-vecs-1显示了一个正则表达式,其中管道字符在字符串中被转义。由于正则表达式在不同平台上有所不同(例如,在 Java 上需要“\|”),因此line-vecs-2使用单个字符(管道)的正则表达式类,从而避免了对管道进行转义的需要。


更新

其他 Clojure 学习资源: