2

当我有一个以空格分隔的键时,如何在不重新创建键的情况下使用它来提取值?

我有一组潜在的键,实际上是列名,作为从 clojure-csv 返回的数据中的第一个序列:(这是为了避免滚动而格式化的。)

["AGY/DIV " "STS" "GIC-ID     " 
"LAST-NAME      " 
"FIRST-NAME     " 
"COVERAGE DESCRIPTION                                   " 
"PREMIUM  " 
"RUN-DATE" 
"BIL MO "]

然后我从这一行创建密钥,并将密钥与每个后续数据行(序列)压缩映射:

(defn create-map-keys
  "Takes a sequence, and turns it into viable keys for a map."
  [in-seq]
  (map (fn [element] (keyword element)) (map #(cstr/trim %1) in-seq)))

; gic-csv-keys    
(:AGY/DIV :STS :GIC-ID :LAST-NAME :FIRST-NAME 
:COVERAGE DESCRIPTION :PREMIUM :RUN-DATE :BIL MO) 

(defn zip-apply-col-nams
   [col-keys row]
   (zipmap col-keys row))

对于测试数据,我将键压缩到 csv 数据的第二行。

(def zm2 (zip-apply-col-nams gic-csv-keys (first gic-csv-data)))

当我尝试从:COVERAGE DESCRIPTION键中提取值时,出现此错误

 (:COVERAGE DESCRIPTION zm2)
CompilerException java.lang.RuntimeException: Unable to resolve symbol: DESCRIPTION in this context, compiling:(NO_SOURCE_PATH:23) 

但是,这有效:

(zm2 (keyword "COVERAGE DESCRIPTION"))
"HARVARD PILGRIM FAMILY - INSURED                       "

我应该修改空格分隔的键以用例如破折号替换空格,还是有另一种方法来引用键而不重新创建它?

谢谢。

4

2 回答 2

6

(keyword "some key") does not "recreate" a keyword, it interns a keyword, meaning that it will always return the same keyword object when given the same name. You can also store the returned keyword and re-use it that way:

(def coverage-description (keyword "COVERAGE DESCRIPTION"))

(coverage-description my-row-map)
于 2012-08-13T16:42:26.673 回答
2

For the record: "some key" is (at the moment) not a valid keyword in Clojure. You should either replace the whitespace with - or _. Or you should go with plain strings as keys and use get.

于 2012-08-14T06:03:38.220 回答