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

后端 未结 4 1305
长情又很酷
长情又很酷 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:26

    Displaying in descending order needs to be outside your search-loop otherwise they will be displayed as they are encountered.

    Sorting in descending order is quite easy using the built-in sorted (you'll need to set the reverse-argument!)

    However python is batteries included and there is already a Counter. So it could be as simply as:

    from collections import Counter
    from operator import itemgetter
    
    def frequencies(filename):
        # Sets are especially optimized for fast lookups so this will be
        # a perfect fit for the invalid characters.
        invalid = set("‘'`,.?!:;-_\n—' '")
    
        # Using open in a with block makes sure the file is closed afterwards.
        with open(filename, 'r') as infile:  
            # The "char for char ...." is a conditional generator expression
            # that feeds all characters to the counter that are not invalid.
            counter = Counter(char for char in infile.read().lower() if char not in invalid)
    
        # If you want to display the values:
        for char, charcount in sorted(counter.items(), key=itemgetter(1), reverse=True):
            print(char, charcount)
    

    The Counter already has a most_common method but you want to display all characters and counts so it's not a good fit in this case. However if you only want to know the x most common counts then it would suitable.

提交回复
热议问题