【发布时间】:2018-08-01 15:13:15
【问题描述】:
这是正在处理的代码,我希望输出为递减计数,如果计数相同,则按名称排序。
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
等等
【问题讨论】:
-
与底层字典一样,
Counter不是有序数据结构。如果订单很重要,请参阅例如stackoverflow.com/questions/35446015/…。或者考虑按键的text.index和值进行排序。
标签: python python-3.x sorting word-count