python - 属性错误 - 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'
解决方案
for line in infile.readlines():
self.stop_word_dict = 1
在这一行中,您将 stop_word_dict 从 dict 更改为 int,稍后在代码中,您尝试访问字典“keys”属性
推荐阅读
- react-native - 自定义导航栏中的 NavigationContainer 问题
- python - 错误计算线性回归模型的成本函数
- java - 来自python的可执行jar
- python - 将 Android LogCat 文本文件结构化为结构化 Pandas DF
- php - WCFM 多供应商市场+ Woocommerce 返回商店/继续购物到单一供应商商店
- xml - 如何使用 XSLT 1.0 对 xml 的多个嵌套元素组进行排序?
- r - 如何将ggplot中x轴的原点从“八月到三月”而不是“一月到三月,八月到十二月”?
- apache-spark - 通过 JDBC 在受限环境中通过流式处理或批处理处理整个 SQL 表
- swift - 链接框架“Pods_Lebsi.framework”缺少此目标所需的一个或多个架构:x86_64 - Xcode
- indexing - 为 xarray 中的每个纬度/经度点选择给定日期的值