2017-06-20 93 views
0

我一直在使用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) 

我们如何解释这种现象?

+0

什么是'helper',它的get()方法做了什么? – DyZ

+0

欢迎来到StackOverflow。请阅读并遵守帮助文档中的发布准则。 [最小,完整,可验证的示例](http://stackoverflow.com/help/mcve)适用于此处。在发布您的MCVE代码并准确描述问题之前,我们无法为您提供有效的帮助。 我们应该能够将发布的代码粘贴到文本文件中,并重现您描述的问题。 – Prune

+0

我已经更新了关于帮助器,但这个get()方法是标准的,它返回对应于一个键的值并返回缺省值的键不存在 –

回答

0
sorted_count = sorted(Word_count_new.items(), key=lambda x: x[1], reverse=True) 

根据用于排序(https://docs.python.org/3/library/functions.html#sorted)的文档,第二个参数是创建从每个列表元素比较键的功能,所以不是字典作为一个整体。

Word_count_new.items()返回一个元组的iterable(在python3中,python2中的列表),这是传递给你的关键函数的东西。如果你希望你的比较键是工作频率的基础(第二个元素),你想返回这个函数中的第二个元素(x[1],其中x是获得比较的单个元组)。

为了解释你得到的随机输出,你的密钥是Word_count_new.get。由于你的字典没有元组作为键,所以默认值是None。

+0

“传递一个元组到这可能会导致一些未定义的行为_” - 为什么这样? – DyZ

+3

传递'tuple'的行为是完全定义的:'.get'不会找到那个元组,并返回'None'。由于'sorted'确保稳定,并且'None'总是与None相比较,所有东西都会按照迭代'.items'通常产生的顺序返回。 –

+0

谢谢!有效。但get函数也会创建该值作为比较键,那么它为什么不起作用? –