I'm trying to count all letters in a txt file then display in descending order

后端 未结 4 1373
长情又很酷
长情又很酷 2021-01-18 08:20

As the title says:

So far this is where I\'m at my code does work however I am having trouble displaying the information in order. Currently it just displays the inf

4条回答
  •  一个人的身影
    2021-01-18 08:38

    You don't need to iterate over 'words', and then over letters in them. When you iterate over a string (like content), you will already have single chars (length 1 strings). Then, you would want to wait untill after your counting loop before showing output. After counting, you could manually sort:

    for letter, count in sorted(counter.items(), key=lambda x: x[1], reverse=True):
        # do stuff
    

    However, better use collections.Counter:

    from collections import Counter
    
    content = filter(lambda x: x not in invalid, content)
    c = Counter(content)
    for letter, count in c.most_common():  # descending order of counts
        print('{:8} appears {} times.'.format(letter, number))
    # for letter, number in c.most_common(n):  # limit to n most
    #     print('{:8} appears {} times.'.format(letter, count))
    

提交回复
热议问题