Clojure - 如何统计字符串中特定单词的数量

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

有人能帮助我吗?我在用Clojure编码,一直试图计算字符串中单词“and”出现的次数。

非常感谢任何帮助。


3
你本可以补充一下你所尝试的内容,这样它不会完全像是需要完成的家庭作业。 - cfrick
1个回答

14

一种方法是使用正则表达式和re-seq函数。这里是一个“天真”的例子:

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

下面是同样的代码,使用treading宏 ->>编写:

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

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

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

这个版本将确保"and"子字符串被非字母字符包围。
如果您想进行不区分大小写的搜索(包括"And"):
(->> string
     (re-seq #"(?i)\band\b")
     count)

另一种解决方案是使用clojure.string命名空间中的split函数

(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)

3
我认为更简单的方法是使用\band\b - m0skit0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接