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

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


当前回答

你可以使用循环和字典。

def count_letter(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

其他回答

a = "I walked today,"
c=['d','e','f']
count=0
for i in a:
    if str(i) in c:
        count+=1

print(count)

最简单的方法是一行代码:

'Mary had a little lamb'.count("a")

但是如果你想用这个也可以:

sentence ='Mary had a little lamb'
   count=0;
    for letter in sentence :
        if letter=="a":
            count+=1
    print (count)

要获得所有字母的计数,请使用集合。计数器:

>>> from collections import Counter
>>> counter = Counter("Mary had a little lamb")
>>> counter['a']
4

python - 3. x:

"aabc".count("a")

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

我知道要求是数一个特定的字母。我在这里没有使用任何方法编写泛型代码。

sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
    if i in count:
        count[i.lower()] = count[i.lower()] + 1
    else:
        count[i.lower()] = 1
print(count)

输出

{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}

现在如果你想要任何特定的字母频率,你可以像下面这样打印。

print(count['m'])
2