如何计算字符串中字符出现的次数?

如。“a”在“Mary had a little lamb”中出现了4次。


当前回答

不使用Counter(), count和regex获得所有字符计数的另一种方法

counts_dict = {}
for c in list(sentence):
  if c not in counts_dict:
    counts_dict[c] = 0
  counts_dict[c] += 1

for key, value in counts_dict.items():
    print(key, value)

其他回答

Str.count (a)是计算字符串中单个字符的最佳解决方案。但是如果你需要统计更多的字符,你就必须读取整个字符串的次数,就像你想要统计的字符一样多。

更好的方法是:

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
    chars[char] += 1

因此,您将有一个dict,它返回字符串中每个字母出现的次数,如果不存在则返回0。

>>>chars['a']
4
>>>chars['x']
0

对于一个不区分大小写的计数器,你可以通过继承defaultdict来覆盖mutator和accessor方法(基类的方法是只读的):

class CICounter(defaultdict):
    def __getitem__(self, k):
        return super().__getitem__(k.lower())

    def __setitem__(self, k, v):
        super().__setitem__(k.lower(), v)


chars = CICounter(int)

for char in text:
    chars[char] += 1

>>>chars['a']
4
>>>chars['M']
2
>>>chars['x']
0

count绝对是计算字符串中字符出现次数的最简洁和有效的方法,但我尝试使用lambda来提出一个解决方案,类似这样:

sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

这将导致:

4

另外,这样做还有一个好处,如果句子是包含上述相同字符的子字符串列表,那么由于使用了in,这也会给出正确的结果。看看吧:

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

这也导致:

4

当然,这只会在检查单个字符的出现时起作用,例如在这种特殊情况下“a”。

myString.count('a');

更多信息请点击这里

正则表达式非常有用,如果你想要区分大小写(当然还有regex的所有功能)。

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

请注意,regex版本的运行时间大约是它的十倍,只有当my_string非常长或代码处于深度循环中时,这才可能成为问题。

python - 3. x:

"aabc".count("a")

Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。