(def string "this is an example string. forever and always and and")
有人能帮助我吗?我在用Clojure编码,一直试图计算字符串中单词“and”出现的次数。
非常感谢任何帮助。
一种方法是使用正则表达式和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)
\band\b
。 - m0skit0