【问题标题】:How to sort the output of a word count [duplicate]如何对字数的输出进行排序[重复]
【发布时间】:2016-10-11 13:17:56
【问题描述】:

所以我有下面的代码来计算文本文件中的单词数。我想按出现次数最多的单词到出现次数最少的单词对输出进行排序。如何实现?

ally = open("alice.txt", "r")
wordcount={}
for word in ally.read().split():
    if word not in wordcount:
        wordcount[word] = 1

    else:
       wordcount[word] += 1

for k,v, in wordcount.items():
    print(k,v)

【问题讨论】:

    标签: python sorting word-count


    【解决方案1】:

    只需使用Counter。它既可以缩短您的代码,又可以为您提供所需的排序。

    引用文档:

    Counter 是一个 dict 子类,用于计算可散列对象。它是一个 无序集合,其中元素存储为字典键和 它们的计数存储为字典值。允许计数 任何整数值,包括零或负数。计数器类 类似于其他语言中的 bag 或 multisets。

    >>> c = Counter(['eggs', 'ham'])
    >>> c['bacon']                              # count of a missing element is zero
    0
    

    【讨论】:

      【解决方案2】:

      您可以使用operator.itemgetter()查看排序后的字典:

      from operator import itemgetter
      
      wordcount = {'test': 1, 'hello': 3, 'test2':0}
      
      sortedWords = sorted(wordcount.items(), key=itemgetter(1), reverse = True)
      

      输出:

      >>> sortedWords
      [('hello', 3), ('test', 1), ('test2', 0)]
      

      【讨论】:

        【解决方案3】:

        这应该为你做:-

        ally = open("alice.txt", "r")
        wordcount={}
        for word in ally.read().split():
            if word not in wordcount:
                wordcount[word] = 1
            else:
               wordcount[word] += 1
        
        for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True):
            print(k,v)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-19
          • 2012-03-15
          • 1970-01-01
          • 1970-01-01
          • 2020-04-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多