首页 > 解决方案 > 属性错误 - int 对象没有属性键 - Python

问题描述

我正在运行这段代码,但我似乎不断收到属性错误,我不知道如何解决这个问题。当我运行它时,我已经包含了代码和 shell 窗口!

# the Count class.  The wordleFromObject function takes a Count object as
# input, and calls its getTopWords method. 

import string
class Count:
    # method to initialize any data structures, such as a dictionary to
    # hold the counts for each word, and a list of stop words
    def __init__(self):
            #print("Initializing Word Counter")
            # set the attrbute wordCounts to an empty dictionary
        self.wordCounts = {}
        infile = open("stop_words.txt", "r")
        self.stop_word_dict = {};
        for line in infile.readlines():
                self.stop_word_dict = 1

    # method to add one to the count for a word in the dictionary.
    # if the word is not yet in the dictionary, we'll need to add a
    # record for the word, with a count of one. 
    def incCount(self,word):
            my_table = str.maketrans('', '', string.punctuation)
            self.wordCounts = {}
            if word in self.stop_word_dict.keys():
                    return
            else:
                    self.stop_word_dict += 1
            cleaned_word = word.translate(my_table).lower()
            if cleaned_word != '':
                if cleaned_word in self.wordCounts.keys():
                        self.wordCounts[cleaned_word] += 1
                else:
                        self.wordCounts[cleaned_word] = 1
    # method to look up the count for a word
    def lookUpCount(self, word):
            return self.wordCounts.get(word.lower(), 0)

def main():
    print("Initializing Word Counter")
    filename = input("Enter book file:")
    infile = open(filename, "r")
    counter = Count()
    for line in infile.readlines():
            words = [word.strip() for word in line.strip().split()]
            for word in words:
                    counter.incCount(word)
    infile.close()
    # Test code for Part 2 and 3  
    # Comment this code once you have completed part 3.
    print(counter.lookUpCount("alice"))
    print(counter.lookUpCount("rabbit"))
    print(counter.lookUpCount("and"))
    print(counter.lookUpCount("she"))
    return
    # Test code for Part 4 and 5
    # topTen = counter.getTopWords(10)
    # print(topTen)

    # Test code for Part 5
    # Import the wordle module and uncomment the call to the wordle function! 
    # wordle.wordleFromObject(counter,30)


# run the main program
main()       

错误信息:

Initializing Word Counter
Enter book file:Alice.txt
Traceback (most recent call last):
line 69, in <module>
main()
line 50, in main
counter.incCount(word)
line 28, in incCount
if word in self.stop_word_dict.keys():
AttributeError: 'int' object has no attribute 'keys'

标签: python

解决方案


for line in infile.readlines():
    self.stop_word_dict = 1

在这一行中,您将 stop_word_dict 从 dict 更改为 int,稍后在代码中,您尝试访问字典“keys”属性


推荐阅读