对计数器中的键和值排序



这是代码正在运行的代码,我希望输出作为降序计数,如果计数是相同的,则按名称订购。

from collections import Counter
import re
from nltk.corpus import stopwords
import operator
text = "The quick brown fox jumped over the lazy dogs bowl. The dog was angry with the fox considering him lazy."
def tokenize(text):
    tokens = re.findall(r"w+|S", text.lower())
    #print(tokens)
    tokens1 = []
    for i in tokens:
        x = re.findall(r"w+|S", i, re.ASCII)
        for j in x:
            tokens1.append(j)
    return tokens
tok = tokenize(text)
punctuations = ['(',')',';',':','[',']',',', '...', '.', '&']
keywords = [word for word in tok if not word in punctuations]
cnt = Counter()
d= {}
for word in keywords:
    cnt[word] += 1 
print(cnt)
freq = operator.itemgetter(1)
for k, v in sorted(cnt.items(), reverse=True, key=freq):
    print("%3d  %s" % (v, k))

当前输出:

  4  the
  2  fox
  2  lazy
  1  quick
  1  brown
  1  jumped
  1  over
  1  dogs
  1  bowl
  1  dog
  1  was
  1  angry
  1  with
  1  considering
  1  him

所需的输出:

  4  the
  2  fox
  2  lazy
  1  angry
  1  bowl
  1  brown
  1  considering
  1  dog
  1  dogs

等。

使用返回元组的排序功能。元组中的第一个项目是计数的倒数(字典中的值(,第二个是字符串(字典中的键(。您可以通过删除变量freq来做到这一点,从而在呼叫中删除关键字reverse,并为字典中的每个项目返回(-Value,key(返回(-value,键(的少量lambda函数。该程序的最后几行是:

print(cnt)
for k, v in sorted(cnt.items(), key=lambda item: (-item[1], item[0])):
    print("%3d  %s" % (v, k))

lambda函数中的符号的原因是获得正确的排序顺序,因为默认排序顺序最低至最高。

最新更新