Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 对向量的每个元素使用拆分_Clojure - Fatal编程技术网

Clojure 对向量的每个元素使用拆分

Clojure 对向量的每个元素使用拆分,clojure,Clojure,基本上,我使用slurp来获取一个文件的内容,该文件应该是一个数据库。我已经对数据进行了一次拆分,得到了一个正确包含所有信息的向量。现在我想再次拆分向量中的每个元素。这会给我一个向量向量。我的问题是,我似乎找不到正确的方法来迭代向量并进行更改。这些更改要么不起作用,要么不存储在向量中 使用doseq: (doseq [x tempVector] (clojure.string/split x #"|") ) 如果我在循环中添加一个print语句,它将打印所有间隔开的内容

基本上,我使用slurp来获取一个文件的内容,该文件应该是一个数据库。我已经对数据进行了一次拆分,得到了一个正确包含所有信息的向量。现在我想再次拆分向量中的每个元素。这会给我一个向量向量。我的问题是,我似乎找不到正确的方法来迭代向量并进行更改。这些更改要么不起作用,要么不存储在向量中

使用doseq:

(doseq [x tempVector]
        (clojure.string/split x #"|")
    )
如果我在循环中添加一个print语句,它将打印所有间隔开的内容,而不做任何更改。
我做错了什么?

函数
str/split
返回一个新的字符串向量,您需要保存它。现在它正在生成,然后被丢弃。你需要这样的东西:

(ns xyz
  (:require
    [clojure.string :as str]))

(def x "hello there to you")
(def y (str/split x #" "))  ; save result in `y`
(def z (str/split x #"e"))  ; save result in `z`

y => ["hello" "there" "to" "you"]
z => ["h" "llo th" "r" " to you"]
您可以在此处在线阅读clojure基础知识:。
我建议买这本书,因为它的内容比在线版多

如果向量中有多个字符串,可以使用
map
函数依次拆分每个字符串:

(def my-strings
  ["hello is there anybody in there?"
   "just nod if you can hear me"
   "is there anyone at home?"])

(def my-strings-split
  (mapv #(str/split % #" ") my-strings))

my-strings-split   => 
  [["hello" "is" "there" "anybody" "in" "there?"]
   ["just" "nod" "if" "you" "can" "hear" "me"]
   ["is" "there" "anyone" "at" "home?"]]

要将含糊不清的文本行重组为单词向量集合,您可以执行以下操作:

(use '[clojure.string :as str :only [split]])

(defn file-as-words [filename re]
  (let [lines      (line-seq (clojure.java.io/reader filename))
        line-words (vec (mapv #(str/split %1 re) lines))]
    line-words))
在这里,我们定义了一个函数,它首先使用
line seq
插入文件并将其拆分为一个行集合,然后映射一个匿名函数,该函数在初始集合的每一行上调用clojure.string/split,将每一行拆分为一个由传入的正则表达式分隔的单词集合。返回单词向量的集合

例如,假设我们有一个名为
/usr/data/test.dat的文件,其中包含

Alice,Eating,001
Kitty,Football,006
May,Football,004
如果我们使用

(file-as-words "/usr/data/test.dat" #",")
你回来

[["Alice" "Eating" "001"] ["Kitty" "Football" "006"] ["May" "Football" "004"]]