我正在编写一个程序来计算 txt 文件中出现次数最多的 20 个单词。当我将它剥离并计数一个文件时,该程序运行良好,但是当我输入两个要剥离和计数的文件时,我收到一条错误消息,指出“'Counter' 对象不可调用”。我很困惑,因为这在一个文档中也能正常工作。下面是我的代码,错误来自 while 循环。谢谢! from collections import Counter numOfData = int(input("How many documents would you liek to scan? ")) i = 0 displayedI = str(i)docList = []finalData = []##Address of document would take 'test.txt' for examplewhile i < numOfData: newAddress = input("Address of document " + displayedI + ": ") docList.append(newAddress) i += 1 print(docList) indexList = 0 for x in docList: file = open(docList[indexList], 'r') data_set = file.read().strip() file.close() split_set = data_set.split() ##This is where the error is occurring Counter = Counter(split_set) most_occuring = Counter.most_common(20) finalData.append(most_occuring) indexList += 1print(finalData)
2 回答
四季花海
TA贡献1811条经验 获得超5个赞
它适用于一个文档的原因是Counter
,最初引用collections.Counter
类的变量Counter
在循环的第一次迭代中被分配了一个实例后,并没有用作构造函数。只有当循环处于第二次迭代时Counter
,现在持有Counter
实例的变量才Counter
通过调用它被用作构造函数,从而产生错误。
添加回答
举报
0/150
提交
取消