在列表上调用Counter函数时出错

时间:2019-02-07 20:46:47

标签: python counter

我正在编写一个程序来计算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 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)

2 个答案:

答案 0 :(得分:2)

我不确定为什么它要对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)

答案 1 :(得分:1)

它在一个文档中起作用的原因是,最初在Counter类中引用的collections.Counter变量在为其分配了Counter实例后,并未用作构造函数循环的第一次迭代。只有在第二次循环中循环时,Counter变量(现在拥有一个Counter实例)才通过调用它而用作Counter构造函数,从而产生错误。