计算字符串中字符的出现次数

计算字符串中字符出现次数的最简单方法是什么?

例如,计算'Mary had a little lamb'出现'a'的次数

答案

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
>>> 'Mary had a little lamb'.count('a')
4
from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter(my_str)
print counter['a']
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
myString.count('a');
"aabc".count("a")
from collections import defaultdict

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

for char in text:
    chars[char] += 1
>>>chars['a']
4
>>>chars['x']
0
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
def check_freq(str):
    freq = {}
    for c in str:
       freq[c] = str.count(c)
    return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}
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))
a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
    print key, a.count(key)