簡體   English   中英

如果按字典值對字典進行排序,我該如何按值對字典進行排序?

[英]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.

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