【问题标题】:Attribute error in python won't go awaypython中的属性错误不会消失
【发布时间】:2014-04-03 17:54:07
【问题描述】:

为什么我总是收到

AttributeError: 'dict_keys' object has no attribute 'sort'

还是我的代码?我该如何解决这个问题?

import string

infile = open('alice_in_wonderland.txt', 'r')

text = infile.readlines()

counts = {}

for line in text:
    for word in line:
    counts[word] = counts.get (word, 0) +1
'''
if word != " ":
if word != ".":
'''         

word_keys = counts.keys()
word_keys.sort()

infile.close()

outfile = open("alice_words.txt", 'w')
outfile.write("Word \t \t Count \n")
outfile.write("======================= \n")
for word in word_keys:
outfile.write("%-12s%d\n" % (word.lower(), counts[word]))
outfile.close()

我不知道还能做什么。

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    要生成排序的键列表,请使用:

    word_keys = sorted(counts)
    

    相反。这适用于 Python 2 和 3。

    在 Python 3 中,dict.keys() 不返回列表对象,而是返回 dictionary view object。您可以在该对象上调用 list(),但 sorted() 更直接,可以为您节省两个额外的调用。

    我看到您似乎在计算文件中的字数;如果是这样,您将改为计算 字符,而不是单词; for word in line: 迭代一个字符串,因此 word 被分配了行中的单个字符。

    您应该改用collections.Counter()

    from collections import Counter
    
    counts = Counter
    
    with open('alice_in_wonderland.txt') as infile:
        for line in infile:
            # assumption: words are whitespace separated
            counts.update(w for w in line.split())
    
    with open("alice_words.txt", 'w') as outfile:
        outfile.write("Word \t \t Count \n")
        outfile.write("======================= \n")
        for word, count in counts.most_common():
            outfile.write("%-12s%d\n" % (word.lower(), counts[word]))
    

    此代码使用文件对象作为上下文管理器(使用with 语句)自动关闭它们。 Counter.most_common() 方法为我们处理排序,不是按键,而是按字数。

    【讨论】:

    • 哇,非常感谢,你就是那个人。出于某种原因,我正试图修复第 9-11 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多