python - Django字典按值排序
问题描述
我正在创建一个网络应用程序,它告诉输入中有多少个单词。我也想发布前 15 个最常用的词。
这是我的代码:
def count(request):
entered_text = request.GET['textarea']
word_list = entered_text.split()
word_dictionary = {}
for word in word_list:
if word in word_dictionary:
word_dictionary[word] += 1
else:
word_dictionary[word] = 1
return render(request,'count.html',
{'alltext':entered_text,
'total':len(word_list),
'dictionary':word_dictionary.items()})
我想word_dictionary
按值排序。
我尝试使用该sorted
功能,但它不起作用。
有什么方法可以排序word_dictionary
吗?
解决方案
你在这里实现的基本上是一个Counter
[python-doc]。ACounter
有一种.most_common(…)
方法可以返回按计数排序的 2 元组列表。因此,您可以使用:
from collections import Counter
def count(request):
entered_text = request.GET['textarea']
word_list = entered_text.split()
word_dictionary = Counter(word_list)
return render(request,'count.html', {
'alltext':entered_text,
'total':len(word_list),
'dictionary':word_dictionary.most_common()
})
编辑:或前 15 个字:
from collections import Counter
def count(request):
entered_text = request.GET['textarea']
word_list = entered_text.split()
word_dictionary = Counter(word_list)
return render(request,'count.html', {
'alltext':entered_text,
'total':len(word_list),
'dictionary':word_dictionary.most_common(15)
})
推荐阅读
- git - 如何在 BitBucket 中查找所有图像
- firebase - Firestore 最近的哪些变化使它抱怨“重叠递归通配符匹配语句”?
- javascript - 包装多个项目js
- web - 如何从网站获取信息
- c# - datagridview:合并具有相同值的多行
- crystal-lang - 在水晶中打印没有内存ID的对象
- python - 如何使用自定义生成器使 tf.data.Dataset.from_generator 产生批次
- php - $_POST 一次又一次地打印相同的值
- botframework - 即使具有完全置信度的意图匹配,LUIS 也无法识别所有实体
- batch-file - 如何在所有子目录中的一个目录中查找pdf文件