Clojure - 如何计算字符串中的特定单词

Clojure - how to count specific words in a string

(def string "this is an example string. forever and always and and")

有人可以帮助我吗?我在 Clojure 中编码,我一直在尝试计算 'and' 这个词在字符串中出现的次数。

非常感谢任何帮助

一种方法是使用正则表达式和 re-seq function。这是一个 "naive" 示例:

(count (re-seq #"and" string))

这是相同的代码,用 treading macro ->>:

编写
(->> string
     (re-seq #"and")
     count)

它会计算子字符串 "and" 在您的 string 中出现的所有次数。这意味着像 panda 这样的词也会被计算在内。但是我们可以通过向正则表达式添加一些限制(使用 "word boundary" metacharacter \b)来仅计算 and 个单词:

(->> string
     (re-seq #"\band\b")
     count)

此版本将确保 "and" 子字符串被非字母字符包围。

如果您想要不区分大小写的搜索(包括 "And"):

(->> string
     (re-seq #"(?i)\band\b")
     count)

另一种解决方案是使用 split function from clojure.string namespace:

(require '[clojure.string :as s])

(->> (s/split string #"\W+") ; split string on non-letter characters
     (map s/lower-case) ; for case-insensitive search
     (filter (partial = "and"))
     count)