关于Clojure:在向量的每个元素上使用split

Using split on each element of a vector

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

使用剂量q:

1
2
3
(doseq [x tempVector]
        (clojure.string/split x #"|")
    )

如果我在循环中添加一条打印语句,它会打印出所有没有变化的空格。
我在做什么错?


要将字词不整齐的行重组为单词向量的集合,您可以执行以下操作:

1
2
3
4
5
6
(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的文件,其中包含

1
2
3
Alice,Eating,001
Kitty,Football,006
May,Football,004

如果我们使用

调用file-as-words

1
(file-as-words"/usr/data/test.dat" #",")

你回来了

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

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

1
2
3
4
5
6
7
8
9
10
(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基础知识:https://www.braveclojure.com。
我建议购买这本书,因为它比在线版本包含更多内容。

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

1
2
3
4
5
6
7
8
9
10
11
12
(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?"]]