问题
I have the word describe
, and I want to see how many times each letter appears in the word. Eg "e" appears twice, "d" appears once etc
I have tried
(for [letter (map str (seq describe))]
(count (re-seq letter describe)))
But I get the error
ClassCastException java.lang.String cannot be cast to java.util.regex.Pattern clojure.core/re-matcher (core.clj:4667)
Any help would be much appreciated
回答1:
You can use frequencies to count the frequency at which each character appears in the string, returning a map like this:
(frequencies "ababacdefg")
=> {\a 3, \b 2, \c 1, \d 1, \e 1, \f 1, \g 1}
This works because the string is being treated as a sequence of characters. frequencies
can be used on general collections:
(frequencies [1 1 2 3])
=> {1 2, 2 1, 3 1}
The key is the value being counted, and the value is the frequency.
来源:https://stackoverflow.com/questions/48567380/count-number-of-times-a-letter-is-in-a-word