在python上查找超过特定次数的字母数?

在python上查找超过特定次数的字母数?,python,string,Python,String,比如说 String = "The boy who cried wolf made many many silly mistakes." def f(n): 应输出: 4 因为只有两个字母,a、m、y和e出现三次以上 到目前为止,我所做的尝试以及我成功达到的目标: String = "The boy who cried wolf made many many silly mistakes." a={} def f(n): for s in String: if s in

比如说

String = "The boy who cried wolf made many many silly mistakes."
def f(n):

应输出:

4
因为只有两个字母,a、m、y和e出现三次以上

到目前为止,我所做的尝试以及我成功达到的目标:

 String = "The boy who cried wolf made many many silly mistakes."
 a={}
 def f(n):
  for s in String:
    if s in a:
      a[s] +=1
    else:
      a[s] = 1
我不确定下一步要做什么

您可以使用“收藏”模块

>>> from collections import Counter
>>> string = "The boy who cried wolf made many many silly mistakes."
>>> Counter(string)
Counter({' ': 9, 'e': 4, 'a': 4, 'y': 4, 'm': 4, 's': 3, 'i': 3, 'o': 3, 'l': 3, 'n': 2, 'd': 2, 'h': 2, 'w': 2, 'T': 1, 'b': 1, '.': 1, 'k': 1, 'r': 1, 't': 1, 'c': 1, 'f': 1})
>>> m = 0
>>> c = Counter(string)
>>> for i in c:
        if i.isalpha() and c[i] > 3:
            m += 1


>>> m
4
将其定义为一个单独的函数

from collections import Counter
def f(n):
    c = Counter(n)
    m = 0
    for i in c:
        if i.isalpha() and c[i] > 3:
            m += 1
    return m
stri = "The boy who cried wolf made many many silly mistakes."    
print f(stri)   
def f(s, n):
    return sum(1 for k,  v in Counter(s).items() if v > n and k.isalpha())
使用及

输出

或者您可以定义一个函数

from collections import Counter
def f(n):
    c = Counter(n)
    m = 0
    for i in c:
        if i.isalpha() and c[i] > 3:
            m += 1
    return m
stri = "The boy who cried wolf made many many silly mistakes."    
print f(stri)   
def f(s, n):
    return sum(1 for k,  v in Counter(s).items() if v > n and k.isalpha())

使用collections.Counter无疑是一个很好的方法;但是,如果您不想导入任何东西,请考虑以下内容:

string = "The boy who cried wolf made many many silly mistakes."
def f(n):
    alpha_chars = filter(lambda char: char.isalpha(), string)
    greater_chars = 0
    for char in list(set(alpha_chars)):
        if string.count(char) > n:
            greater_chars += 1
    return greater_chars
其中f3将输出4

但是,最好使用字符串作为参数

my_string = "The boy who cried wolf made many many silly mistakes."
def f(string, n):
    ...

然后,您可以使用fmy_字符串3调用,它将输出4。

y,e是什么?再次检查e是的,您是对的。谢谢大家的回复。但是我可以要求你使用像fn这样的函数。我现在不确定采集模块到底是什么现在这是一个完美的答案很好的答案,但您的函数不支持任何任意数字。
string = "The boy who cried wolf made many many silly mistakes."
def f(n):
    alpha_chars = filter(lambda char: char.isalpha(), string)
    greater_chars = 0
    for char in list(set(alpha_chars)):
        if string.count(char) > n:
            greater_chars += 1
    return greater_chars
my_string = "The boy who cried wolf made many many silly mistakes."
def f(string, n):
    ...