Letter Frequency Counter

  • Share this:

Code introduction


Counts the occurrences of each letter in a given text and returns a dictionary containing the letter and its count.


Technology Stack : collections.Counter, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
def a_to_z_counter(text):
    from collections import Counter
    import string
    
    # Count the occurrences of each letter in the text
    counter = Counter(text)
    
    # Filter out non-alphabet characters and sort the letters
    sorted_letters = sorted([char for char in counter if char.isalpha()])
    
    # Create a dictionary with the counts of each letter
    letter_counts = {letter: counter[letter] for letter in sorted_letters}
    
    return letter_counts