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

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


当前回答

拿起这个用户的评论:

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。你也可以在单词列表中计算唯一的单词。

其他回答

“不使用计数查找字符串中需要的字符”方法。

import re

def count(s, ch):

   pass

def main():

   s = raw_input ("Enter strings what you like, for example, 'welcome': ")  

   ch = raw_input ("Enter you want count characters, but best result to find one character: " )

   print ( len (re.findall ( ch, s ) ) )

main()

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

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)

不使用Counter(), count和regex获得所有字符计数的另一种方法

counts_dict = {}
for c in list(sentence):
  if c not in counts_dict:
    counts_dict[c] = 0
  counts_dict[c] += 1

for key, value in counts_dict.items():
    print(key, value)

正则表达式?

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