(def string "this is an example string. forever and always and and")
有人可以帮我吗?我使用Clojure进行编码,并且一直在尝试计算单词“和”在字符串中出现的次数。
任何帮助深表感谢
一种方法是使用正则表达式和re-seq
函数。这是一个“天真”的例子:
(count (re-seq #"and" string))
这是用踩踏宏->>
编写的相同代码:
(->> string
(re-seq #"and")
count)
它将计算您的中所有子字符串的"and"
出现string
。这意味着像p和a这样的词也将被计算在内。但是,我们可以and
通过对正则表达式添加一些限制(使用“单词边界”元字符\b
)来仅对单词计数:
(->> string
(re-seq #"\band\b")
count)
此版本将确保"and"
子字符串被非字母字符包围。
而且,如果您希望使用不区分大小写的搜索(包括"And"
):
(->> string
(re-seq #"(?i)\band\b")
count)
另一种解决方案是使用命名空间中的split
函数clojure.string
:
(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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句