Clojure比较文件中的行



我必须写一个clojure函数来比较文件中的行。我的文件包含如下信息:

{:something1 1
    :something2 2
    :something2 2
    :something3 3
    :something4 4
    :something4 4
}

可以看到它是用来定义散列的。我想在我的程序中导入哈希值,但在此之前,我需要删除与其他行相等的每一行。我的台词必须是独一无二的。我该怎么做呢?

(defn read-map-wo-dups [fname]
  (into {}
   (with-open [r (reader fname)]
     (doall (distinct
             (map #(read-string
                    (str "[" (replace % #"[{}]" "") "]"))
                  (line-seq r)))))))
测试:

data.dat包含:

{:something1 1
 :something2 2
 :something2 2
 :something3 3
 :something3 3
 :something4 4}
结果:

(read-map-wo-dups "data.dat")
=> {:something1 1, :something2 2, :something3 3, :something4 4}

这可以分解成更简单的步骤,然后线程化成一个简单的"一行"

(->> (slurp "data")         ; read the data from the file.
     (re-seq #"[^{} n]+")  ; split it into strings ignoring n and { }.
     (partition 2)          ; group it into key, value pairs
     (map vec)              ; turn the pairs into vectors because into wants this.
     (into {}))             ; mash them in turn into a single map.
{":something1" "1", ":something2" "2", ":something3" "3", ":something4" "4"}

或者,如果您喜欢嵌套的形式,您可以像这样编写相同的代码:

user> (into {} (map vec (partition 2 (re-seq #"[^{} n]+" (slurp "data")))))
{":something1" "1", ":something2" "2", ":something3" "3", ":something4" "4"}

相关内容

  • 没有找到相关文章

最新更新