[英]How would I sort this Dictionary by value then if the same sort it by key value?
# Imports the sys library
import sys
# Returns the file's contents
def readFile():
return open("gettysburg.txt", "r").read()
# Writes to the file with the variable output
def writeFile(output):
open("out.out", "w").write(output)
# Returns all of the words of the variable content by splitting the string by the space
def getWords(content):
return content.replace("--", " ").replace("\n", " ").replace(".", "").replace("!", "").replace(",", "").replace("?", "").split(" ")
def main():
# Initiates a HashMap
wordCounts = dict()
for text in getWords(readFile()):
# Checks if the string is empty
if (text != ""):
# If the text is not in variable wordCounts then add it to the wordCounts makes it = 1 else then increment it by 1
if (not text in wordCounts):
wordCounts[text] = 1
else:
wordCounts[text] = wordCounts[text] + 1
print(wordCounts)
for i in range(0, 9):
print(sorted(wordCounts, key=wordCounts.__getitem__, reverse=True)[i])
main()
我如何按值对wordCounts排序,然后按键对其排序?
我无法使用任何类型的库,因此请不要建议使用任何库来提高效率。
我有点为难。
关于我在做什么的一些见解:
基本上,我正在查找带有文本块的单词频率,然后根据值按字母顺序将其打印出来。
d = dict()
d["a"] = 10
d["ab"] = 8
d["abc"] = 10
d["bc"] = 9
for value, key in sorted(zip(d.values(), d.keys())):
print(value, key)
输出:
8 ab
9 bc
10 a
10 abc
这是您想要的输出吗?
d = dict()
d['that']= 13
d['the']=9
d['to']=8
d['we']=8
d['here']=8
d['a']=7
d['and']=6
d['nation']=5
d['not']=5
d['for']=5
d['can']=5
d['of']=5
d['have']=5
ordered = dict()
for e in d:
if d[e] not in ordered:
ordered[d[e]] = []
ordered[d[e]].append(e)
for e in reversed(sorted(ordered.keys())):
for v in sorted(ordered[e]):
print e, v
输出:
13 that
9 the
8 here
8 to
8 we
7 a
6 and
5 can
5 for
5 have
5 nation
5 not
5 of
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.