1

由于记录是不可变的,我无法读取数据并在没有它自己创建新实例的情况下对其进行解析。此外,我如何能够从许多特定列中读取我的 excel 文件,而不是从第 0 列读取到 EOF。无论如何,我是否可以从第 1 列、第 3 列、第 5 列读取数据。假设第 1 列将被解析为字符串,第 3 列将解析为整数,第 5 列将解析为长整数。

(defrecord Record [Name Age Index])

(defn read-csv [fname count]
  (with-open [file (io/reader fname)]
    (doall (take count (map (comp first csv/read-csv)
                            (line-seq file))))))
(def records (map #(apply ->Record %) (read-csv "C:/Users/user/Documents/URECA/hi/lib/test.csv" 1)))

这就是我所拥有的,但它似乎是在逐步阅读这些列

4

1 回答 1

1

要保留文本字段的引号,您可以通过正则表达式解析 csv 文件:

(defn read-csv [fname count]
  (with-open [file (io/reader fname)]
    (doall (map #(str/split % #",") ; doesn't work with commas in text fields
                (take count (line-seq file))))))

(defn make-record [idxs types row]
  (apply ->Record
         (map (fn [idx t]
                (let [value (nth row idx)]
                  (case t
                    :string value
                    :int (Integer/parseInt value)
                    :long (Long/parseLong value))))
              idxs types)))

(def records (map (partial make-record
                           [0 2 4]
                           [:string :int :long])
                  (read-csv "/home/mobyte/test.csv" 3)))

(pprint records)
-> ({:Name "\"s1\"", :Age 1, :Index 111}
    {:Name "\"s2\"", :Age 2, :Index 112}
    {:Name "\"s3\"", :Age 3, :Index 113})

(type (:Age (first records)))
->java.lang.Integer

(type (:Index (first records)))
-> java.lang.Long

(type (:Name (first records)))
-> java.lang.String     
于 2013-01-02T06:32:49.587 回答