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

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


当前回答

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

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

其他回答

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

'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

我不知道“最简单的”,但简单的理解可以做到:

>>> my_string = "Mary had a little lamb"
>>> sum(char == 'a' for char in my_string)
4

利用内置的和,生成器理解和bool是整数的子类的事实:如何乘字符等于'a'。

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

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

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