Letter Frequency Calculation in Python

  • Share this:

Code introduction


Calculates and returns the frequency of each letter in the string, letters are case-insensitive, and sorted by letter order.


Technology Stack : collections.Counter, string

Code Type : String processing

Code Difficulty : Intermediate


                
                    
def a_to_z_frequency(text):
    """
    计算字符串中每个字母的频率,并返回按字母顺序排列的频率列表。
    """
    from collections import Counter
    import string
    
    # 计算字母频率
    letters_only = ''.join(filter(str.isalpha, text)).lower()
    letter_counts = Counter(letters_only)
    
    # 按字母顺序排列
    sorted_letter_counts = dict(sorted(letter_counts.items()))
    
    return sorted_letter_counts