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

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

    You can sort your dictionary at the time you print, with the sorted method:

    lettercount = {}
    invalid = "‘'`,.?!:;-_\n—' '"
    infile = open('text.file')
    for c in infile.read().lower():
        if c not in invalid:
            lettercount[c] = lettercount.setdefault(c,0) + 1
    for letter in sorted(lettercount):
        print("{} appears {} times".format(letter,lettercount[letter]))
    

    Rmq: I used setdefault change method to set the default value to 0 when we meet a letter for the first time

提交回复
热议问题