簡體   English   中英

對計數器中的鍵和值進行排序

[英]Sorting the keys and values in counter

這是正在處理的代碼,我希望輸出為降序計數,如果計數相同,則按名稱排序。

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 、在 sorted 調用中刪除關鍵字reverse並提供一個小 lambda 函數來為字典中的每個項目返回 (-value, key) 來實現這一點。 程序的最后幾行是:

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

在 lambda 函數中使用 - 符號的原因是為了獲得正確的排序順序,因為默認排序順序是從最低到最高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM