计算一个单词中一个字母的次数 [英] Count number of times a letter is in a word

查看:105
本文介绍了计算一个单词中一个字母的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 describe 这个词,我想看看每个字母出现在单词中的次数。例如, e出现两次, d出现一次等等

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

我尝试过

    (for [letter (map str (seq describe))] 
      (count (re-seq letter describe)))

但出现错误

ClassCastException java.lang.String cannot be cast to java.util.regex.Pattern  clojure.core/re-matcher (core.clj:4667)

任何帮助将不胜感激

推荐答案

您可以使用 频率 计算每个字符在字符串中出现的频率,并返回如下映射:

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.

这篇关于计算一个单词中一个字母的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆