Contar las ocurrencias numéricas de un carácter en una cadena


¿Cuál es la forma más sencilla de contar el número de ocurrencias de un carácter en una cadena?

Por ejemplo, contar el número de veces que 'a' aparece en 'Mary had a little lamb'

Author: codeforester, 2009-07-21

17 answers

Str.count (sub [, start [, end]])

Devuelve el número de ocurrencias no superpuestas de subcadena sub en el rango [start, end]. Los argumentos opcionales start y end se interpretan como en notación de corte.

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
 1063
Author: Ogre Codes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-01 07:16:28

Puedes usar count() :

>>> 'Mary had a little lamb'.count('a')
4
 121
Author: eduffy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-05 07:24:55

Como dijeron otras respuestas, usar el método de cadena count() es probablemente el más simple, pero si lo haces con frecuencia, echa un vistazo a colecciones.Contador:

from collections import Counter
str = "Mary had a little lamb"
counter = Counter(str)
print counter['a']
 81
Author: Brenden Brown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-08 11:49:25

Expresiones regulares tal vez?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
 46
Author: Sinan Taifour,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-20 20:03:19
myString.count('a');

Más información aquí

 23
Author: Finer Recliner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-20 20:04:47
"aabc".count("a")
 14
Author: Aaron Fi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-20 20:05:03

Las expresiones regulares son muy útiles si se quiere insensibilidad a mayúsculas y minúsculas (y por supuesto toda la potencia de las expresiones regulares).

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

Tenga en cuenta que la versión regex toma el orden de diez veces más tiempo para ejecutarse, lo que probablemente será un problema solo si my_string es tremendamente largo, o el código está dentro de un bucle profundo.

 8
Author: jafelds,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-05 17:04:28
a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
    print key, a.count(key)
 5
Author: rookie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-24 22:37:37

str.count(a) es la mejor solución para contar un solo carácter en una cadena. Pero si necesita contar más caracteres, tendría que leer toda la cadena tantas veces como caracteres desee contar.

Un mejor enfoque para este trabajo sería:

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
    chars[char] += 1

Así que tendrás un dict que devuelve el número de ocurrencias de cada letra en la cadena y 0 si no está presente.

>>>chars['a']
4
>>>chars['x']
0

Para un contador insensible a mayúsculas y minúsculas, podría anular el mutador y el accessor métodos por subclase defaultdict (los de la clase base son de solo lectura):

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
 5
Author: Nuno André,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-22 14:16:39

Esta función fácil y directa podría ayudar:

def check_freq(str):
    freq = {}
    for c in str:
       freq[c] = str.count(c)
    return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}
 3
Author: Erick Mwazonga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-20 13:36:17
str = "count a character occurance"

List = list(str)
print (List)
Uniq = set(List)
print (Uniq)

for key in Uniq:
    print (key, str.count(key))
 2
Author: Thiru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-01 02:36:06

count es sin duda la forma más concisa y eficiente de contar la ocurrencia de un carácter en una cadena, pero traté de llegar a una solución utilizando lambda, algo como esto:

sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

Esto resultará en :

4

Además, hay una ventaja más de esto es que si la oración es una lista de sub-cadenas que contienen los mismos caracteres que la anterior, entonces también esto da el resultado correcto debido al uso de in. Echa un vistazo :

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

Esto también resulta en:

4

Pero, por supuesto, esto funcionará solo cuando se verifique la ocurrencia de un solo carácter como 'a' en este caso particular.

 2
Author: Satish Garg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-28 17:22:51

"Sin usar count para encontrar el carácter que desea en el método string".

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()
 1
Author: B-Y,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-07 22:49:32
spam = 'have a nice day'
var = 'd'


def count(spam, var):
    found = 0
    for key in spam:
        if key == var:
            found += 1
    return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))
 0
Author: rookie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-15 19:09:25

No más que esto en mi humilde opinión - puede agregar los métodos superior o inferior

def count_letter_in_str(string,letter):
    return string.count(letter)
 0
Author: Tim Seed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-23 19:16:31

Usando Count:

string = "count the number of counts in string to count from."
x = string.count("count")

X = 2.

 0
Author: Carlson Bimbuh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-21 22:04:22

Esto le dará la ocurrencia de cada carácter en una cadena. O / P también está en formato de cadena:

def count_char(string1):
string2=""
lst=[]
lst1=[]
for i in string1:
    count=0
    if i not in lst:
        for j in string1:
            if i==j:
                count+=1
        lst1.append(i)
        lst1.append(count)
    lst.append(i)

string2=''.join(str(x) for x in lst1)
return string2 

print count_char("aabbacddaabbdsrchhdsdg")
 -2
Author: abhishek narayan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-22 09:48:47