1

将第 3 列的这行 CSV 转换为 Clojure 列表的最佳方法是什么?

357302041352401, 2012-08-27 19:59:32 -0700, 100, ["SNIA34", "M33KLC", "M34KLC", "W35REK", "SRBT", "MODE", "BFF21S", "CC12", "RCV56V", "NBA1", "RESP", "A0NTC", "PRNK", "WAYS", "HIRE", "BITE", "INGA1", "M32MOR", "TFT99W", "TBF5P", "NA3NR"]
4

3 回答 3

2

假设您已经可以读取 csv 文件...

您可以将read-stringinto结合使用

user=> (def your_csv_column "[\"SNIA34\", \"M33KLC\", \"M34KLC\"]")
#'user/your_csv_column
user=> (into '() (read-string your_csv_column))
("M34KLC" "M33KLC" "SNIA34")
于 2012-08-28T16:56:52.697 回答
2

您可以使用Clojure Csv来做到这一点。

于 2012-08-28T20:10:08.360 回答
1

你的数据很有趣,它似乎包括一个传统的逗号分隔行,后面是括号中的数据。我无法完全确定括号中的数据是您在 .csv 文件中的表示还是在阅读后想要的表示,但无论哪种方式,这都是我读取 .csv 文件的方式:

我的图书馆使用 clojure-csv 的 project.clj:

(defproject util "1.0.4-SNAPSHOT"
  :description "A general purposes Clojure library"
  :dependencies [[org.clojure/clojure "1.4.0"]
                 [clojure-csv/clojure-csv "1.3.2"]]
  :aot [util.core]
  :omit-source true)

我的图书馆的 core.clj 标头:

(ns util.core
  ^{:author "Charles M. Norton",
    :doc "util is a Clojure utilities directory containing things
          most Clojure programs need, like cli routines.
        Created on April 4, 2012"}

  (:require [clojure.string :as cstr])
  (:import java.util.Date)
  (:import java.io.File)
  (:use clojure-csv.core))

我的库函数返回解析为向量向量的 .csv 文件。

(defn ret-csv-data
"Returns a lazy sequence generated by parse-csv.
 Uses open-file which will return a nil, if
 there is an exception in opening fnam.

 parse-csv called on non-nil file, and that
 data is returned."

 [fnam]
 (let [  csv-file (open-file fnam)

   inter-csv-data (if-not (nil? csv-file)
                    (parse-csv csv-file)
                     nil)

  csv-data (vec (filter #(and pos? (count %) (not (nil? (rest %)))) 
            inter-csv-data))]

    ;removes blank sequence at EOF.                
    (pop csv-data)))

(defn fetch-csv-data
    "This function accepts a csv file name, and returns parsed csv data,
     or returns nil if file is not present."

    [csv-file]
        (let [csv-data (ret-csv-data csv-file)]
            csv-data))

我发现非常有帮助的是避免使用 nth——来自 SO 和其他来源的非常有用的建议——并且鉴于我的大部分 .csv 数据来自数据库查询,我将列压缩到每个 .csv 序列(行),并且然后通过映射键对该数据进行操作。它为我简化了事情。

于 2012-08-29T12:24:56.550 回答