给定由 clojure-csv 解析的以下向量
[“123/45678”“RET”“xxx-yy-zzzz”“TOAST”“法国”“某种保险 - 保险”“0”“12345678”“102020”]
nth 在以下函数中导致异常。
(defn reduce-csv-row
"Accepts a csv-row and a list of columns to extract, and
reduces the csv-row to the selected list."
[csv-row col-nums]
(reduce
(fn [out-csv-row col-num]
;Without testing for empty, a
;java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
;would occur if the file contained a blank line.
(let [temp-val
(try
(nth csv-row col-num nil)
(catch Exception e (do
(println csv-row, " ", col-num)
(.getMessage e))))])
(conj out-csv-row (nth csv-row col-num nil)))
[]
col-nums))
try .. catch 最终会消失,我只想要最少的调试打印输出。
对于我的生活,我无法弄清楚为什么 nth 会引发异常。它不在repl。另一个带有引号字段的 .csv 文件中的数据,与我包含的示例行非常相似,不会失败。我认为这是由于一些我看不到的微妙之处。
我将不胜感激任何帮助或解决此问题的方法。
谢谢你。
编辑:
使用上面的第一种方法,我收到一个错误,指出 Java 字符串无法转换为整数。
使用此函数将掩码向量转换为整数:
(defn cvt-mask-numeric
"Converts a vector mask to numbers. It was read from a file, so it's a series of strings.
Build in some protection in case we get a non-string. Don't want stuff to blow up."
[csv-mask]
(map #(utl/parse-int %) csv-mask))
使用以下方法
(defn reduce-csv-row
"Accepts a csv-row and a list of columns to extract, and
reduces the csv-row to the selected list."
[csv-row col-nums]
(try
(map #(nth csv-row %) col-nums)
(catch Exception e (.getMessage e) (println csv-row, " ", col-nums))))
我得到一个 java.lang.IndexOutOfBoundsException
问题是我忘记通过转换器传递第二个掩码:
(let [bene-csv-data (bcsv/strip-csv-header (fetch-csv-data (:ifn1 opts)))
bene-csv-mask (bcsv/cvt-mask-numeric (first (fetch-csv-data (:ifm1 opts))))
gic-csv-data (bcsv/strip-csv-header (fetch-csv-data (:ifn2 opts)))
gic-csv-mask (first (fetch-csv-data (:ifm2 opts)))
感谢您的评论,因为他们帮助我回去看看。