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

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


当前回答

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

'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)

其他回答

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

'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)
a = "I walked today,"
c=['d','e','f']
count=0
for i in a:
    if str(i) in c:
        count+=1

print(count)

拿起这个用户的评论:

import numpy as np
sample = 'samplestring'
np.unique(list(sample), return_counts=True)

Out:

(array(['a', 'e', 'g', 'i', 'l', 'm', 'n', 'p', 'r', 's', 't'], dtype='<U1'),
 array([1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1]))

检查“年代”。可以通过如下方式过滤两个数组的元组:

a[1][a[0]=='s']

旁注:它的工作原理类似于集合包的Counter(),只是在numpy中,无论如何都要导入numpy。你也可以在单词列表中计算唯一的单词。

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

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