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

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


当前回答

a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
    print(key, a.count(key))

其他回答

这个简单直接的函数可能会有帮助:

def check_freq(x):
    freq = {}
    for c in set(x):
       freq[c] = x.count(c)
    return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}

如果需要理解:

def check_freq(x):
    return {c: x.count(c) for c in set(x)}

Python 3

有两种方法可以做到这一点:

1)内置函数count()

sentence = 'Mary had a little lamb'
print(sentence.count('a'))`

2)不使用函数

sentence = 'Mary had a little lamb'    
count = 0

for i in sentence:
    if i == "a":
        count = count + 1

print(count)

正则表达式?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))

这是公认答案的延伸,你应该在文本中寻找所有字符的计数。

# Objective: we will only count for non-empty characters

text = "count a character occurrence"
unique_letters = set(text)
result = dict((x, text.count(x)) for x in unique_letters if x.strip())

print(result)
# {'a': 3, 'c': 6, 'e': 3, 'u': 2, 'n': 2, 't': 2, 'r': 3, 'h': 1, 'o': 2}

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”。