Counting Letter Frequency in a String (Python)

how to count the frequency of letters in text excluding whitespace and numbers?

This should work:

>>> from collections import Counter
>>> from string import ascii_letters
>>> def count_letters(s) :
... filtered = [c for c in s.lower() if c in ascii_letters]
... return Counter(filtered)
...
>>> count_letters('Math is fun! 2+2=4')
Counter({'a': 1, 'f': 1, 'i': 1, 'h': 1, 'm': 1, 'n': 1, 's': 1, 'u': 1, 't': 1})
>>>

Python - Counting Letter Frequency in a String

Does this satisfy your needs?

from itertools import groupby
s = "bbbaaac ddddee aa"

groups = groupby(s)
result = [(label, sum(1 for _ in group)) for label, group in groups]
res1 = "".join("{}{}".format(label, count) for label, count in result)
# 'b3a3c1 1d4e2 1a2'

# spaces just as spaces, do not include their count
import re
re.sub(' [0-9]+', ' ', res1)
'b3a3c1 d4e2 a2'

Count the number of occurrences of a character in a string

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

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

Count occurrence of all letters in string (python)

You can do it using collections.Counter():

from collections import Counter
str_count = Counter(message)
print(str(str_count))

Or if you want to use loops:

str_count = {}

for i in message:
if i in str_count:
str_count[i] += 1
else:
str_count[i] = 1

print(str(str_count)

More pythonic way:

str_count = {i : message.count(i) for i in set(message)}

print(str(str_count)

Counting the Frequency of Letters in a string (Python)

You could just check the input with if else and raise an Error if needed with a custom message

if original_input == "":
raise RuntimeError("Empty input")
else:
# Your code goes there

As a side not, input() is enough, no need to add quotes ""

Edit: This question was edited, the original question was to check if an input is empty.

Second edit:

If you want your code to print letters as in your output, you should iterate over your word instead over your alphabet:

for c in word:
print("The letter", c ,"occured", word.count(c), "times")

Counting each letter's frequency in a string

In 2.7+:

import collections
letters = collections.Counter('google')

Earlier (2.5+, that's ancient by now):

import collections
letters = collections.defaultdict(int)
for letter in word:
letters[letter] += 1


Related Topics



Leave a reply



Submit