Counting English Letters in Text

  • Share this:

Code introduction


This function takes a string argument and returns a dictionary containing the count of each English letter (case insensitive) in the string.


Technology Stack : collections, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
def a_to_z_counter(text):
    """
    计算给定文本中每个字母(忽略大小写)的出现次数,并返回一个包含字母及其出现次数的字典。
    """
    from collections import Counter
    from string import ascii_lowercase

    # 将文本转换为小写并计算每个字母的出现次数
    lower_text = text.lower()
    letter_counts = Counter(lower_text)

    # 过滤掉不在字母表中的字符,只保留26个英文字母
    filtered_counts = {letter: count for letter, count in letter_counts.items() if letter in ascii_lowercase}

    return filtered_counts

# 代码示例
text = "Hello, World! This is a simple test to count letters from a to z."
result = a_to_z_counter(text)
print(result)