Clojure 字符串替换带有文本的地图向量

Kin*_*one 1 algorithm clojure

我想用其中的文本替换地图向量中的某些字符。

这应该是一个更大的程序的一部分,它会计算文本列表中的所有单词。

输入向量如下所示:

[{:text "bla. Bla! Blabla, foo"}
   {:text "hello foo? bla Foo, blabla"}
   {:text "bla blub Foo Bla blub"}]
Run Code Online (Sandbox Code Playgroud)

输出应如下所示,并应按值排序:

{:bla 3 :Bla 2 :blub 2 :foo 2 :Foo 2 ... } 
Run Code Online (Sandbox Code Playgroud)

但首先我想从某些字符中清除字符串。

我用 map 尝试过,但我不明白为什么这段代码不能正常工作:

(defn clean-texts []
  (map (fn [x] (clojure.string/replace x #"[.,]" "")) (:text texts)))
Run Code Online (Sandbox Code Playgroud)

整个代码如下所示:

(ns keyword-finder.core
  (:gen-class))

(def texts
  [{:text "bla. Bla! Blabla, foo"}
   {:text "hello foo? bla Foo, blabla"}
   {:text "bla blub Foo Bla blub"}])

(defn clean-texts []
  (map (fn [x] (clojure.string/replace x #"[.,]" "")) (:text texts))
)
Run Code Online (Sandbox Code Playgroud)

Die*_*sch 5

你想要的是这样的:

(defn tokenize [s]
  (-> s
    (.replaceAll "[^a-zA-Z\\s]" "")
    (clojure.string/split #" ")))
Run Code Online (Sandbox Code Playgroud)

这会从字符串中删除所有非字母,因此当应用于“bla. blah, blah”时,它会给你“bla blah blah”

(defn word-counts [texts]
  (let [tokens
    (->> texts
        (map (comp tokenize :text))
        (apply concat)
        (map keyword))]
   (frequencies tokens)))
Run Code Online (Sandbox Code Playgroud)

此函数从映射中提取键 :text 的值,应用于tokenize所有结果字符串,将它们连接成单词列表,将它们转换为关键字,最后使用内置函数返回关键字计数frequencies

(word-counts texts)
Run Code Online (Sandbox Code Playgroud)

产生 {:bla 3, :Bla 2, :Blabla 1, :foo 2, :hello 1, :Foo 2, :blabla 1, :blub 2}