我一直在使用Sorting_Dictionary中提供的解決方案根據值排序字典。我知道字典不能像這樣排序,但一個排序的斑點列表可以獲得。通過排序字典在python通過使tuplles排序列表不起作用
完整代碼:
import sys
import pprint
def helper(filename):
Word_count={}
f=open(filename)
for line in f:
words=line.split()
for word in words:
word=word.lower()
Word_count.setdefault(word,0)
Word_count[word]+=1
f.close()
return Word_count
def print_words(filename):
Word_count_new=helper(filename)
sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
for word in sorted_count:
pprint.pprint(word)
def print_top(filename):
word_list=[]
Word_count=helper(filename)
word_list=[(k,v) for k,v in Word_count.items()]
for i in range(20):
print word_list[i] + '\n'
###
# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topcount} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()
此功能將產生問題:
def print_words(filename):
Word_count_new=helper(filename)
sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
for word in sorted_count:
pprint.pprint(word)
這裏幫手是返回一個字典是進行排序的方法。字典是這樣的{爸爸:1,媽媽:2,寶貝:3}
但是這不會產生一個排序列表的結果。相反,輸出是隨機的,這樣的
('he', 111)
("hot-tempered,'", 1)
('made', 29)
('wise', 2)
('whether', 11)
('wish', 21)
('scroll', 1)
('eyes;', 1)
('this,', 17)
('signed', 2)
('this.', 1)
我們如何解釋這種現象?
什麼是'helper',它的get()方法做了什麼? – DyZ
歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。在發佈您的MCVE代碼並準確描述問題之前,我們無法爲您提供有效的幫助。 我們應該能夠將發佈的代碼粘貼到文本文件中,並重現您描述的問題。 – Prune
我已經更新了關於幫助器,但這個get()方法是標準的,它返回對應於一個鍵的值並返回缺省值的鍵不存在 –