English character frequency statistics (Python)

Write a program that analyzes the frequency of letters a~z appearing in a given string, ignoring case, and outputs it in descending order.

def eng(txt):             #定义一个函数  
    txt.lower()           #全部小写
    count= {}             #定义一个字典
    for word in txt:
        if word in "abcdefghijklmnopqrstuvwxyz":
            count[word] = count.get(word,0) + 1         #根据键信息查找并返回值信息
    txtitems = list(count.items())                      #将字典转换为列表才可以进行排序
    txtitems.sort(key = lambda x:x[1],reverse = True)   # 根据值进行降序排序,默认是升序
    for i in range(len(txtitems)):                      #0到len(items),不包括len(items)作为下标,循环遍历列表items中的键值,分别赋值给变量word,count
        word,count = txtitems[i]
        print("{:<10}{:<5}".format(word,count))
    return txt  
 
x=input("请输入一段英文字符:")
eng(x)

Results of running the program:

请输入一段英文字符: ababa
a         3    
b         2   

Guess you like

Origin blog.csdn.net/greatau/article/details/134065683
Recommended