首页 > 解决方案 > 在列表上调用 Counter 函数时出错

问题描述

我正在编写一个程序来计算 txt 文件中出现次数最多的 20 个单词。当我将其剥离并计数一个文件时,该程序运行良好,但是当我输入两个要剥离和计数的文件时,我收到一条错误消息,提示“'Counter' object is not callable”。我很困惑,因为这同样适用于一个文档。下面是我的代码,错误来自 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 example
while 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 += 1


print(finalData)

标签: pythoncounter

解决方案


我不确定为什么它适用于 1 个元素,但是,您可以尝试更改变量的名称,因为Counter是对象可调用名称。

还在您的索引上添加一些“更好”的做法。

for idx, x in enumerate(docList):
    file = open(docList[idx], 'r')
    data_set = file.read().strip()
    file.close()
    split_set = data_set.split()
    CounterVariable = Counter(split_set)
    most_occuring = CounterVariable.most_common(20)
    finalData.append(most_occuring)

推荐阅读