(def string "this is an example string. forever and always and and")
有人可以帮我吗?我在Clojure中编写代码,我一直在计算字符串'and'出现在字符串中的次数。Clojure - 如何计算字符串中的特定字词
任何的帮助深表感谢
(def string "this is an example string. forever and always and and")
有人可以帮我吗?我在Clojure中编写代码,我一直在计算字符串'and'出现在字符串中的次数。Clojure - 如何计算字符串中的特定字词
任何的帮助深表感谢
一种方式来做到这一点是使用正则表达式和re-seq
function。这里是一个“天真”的例子:
(count (re-seq #"and" string))
这里是相同的代码,用treading macro ->>
写着:
(->> string
(re-seq #"and")
count)
它将算子串"and"
的所有出场的string
。这意味着像p 和 a这样的词也会被计算在内。但是,我们可以通过添加一些限制正则表达式(使用"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)
我觉得比较简单的就是'\ band \ b'。 – m0skit0 2015-03-13 20:24:22
@ m0skit0好抓! – 2015-03-14 02:15:39
,你尝试过什么,所以它不看起来完全像功课,这需要做。 – cfrick 2015-03-13 19:51:55