Reputation: 41
I am writing a program to count the 20 most occurring words in a txt file. The program is working fine when I have it strip and count one file but when I input two files to be stripped and counted I get an error saying "'Counter' object is not callable". I am confused because again this is working fine with one document. Below is my code and the error is coming from within the while loop. Thanks!
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)
Upvotes: 1
Views: 6023
Reputation: 106553
The reason why it works for one document is because the Counter
variable, originally referencing the collections.Counter
class, is not used as a constructor after it is assigned with a Counter
instance in the loop's first iteration. It's only when the loop is in the second iteration that the Counter
variable, now holding a Counter
instance, is used as a Counter
constructor by calling it, thereby producing the error.
Upvotes: 2
Reputation: 638
I'm not sure why is it working on 1 element, however, you could try to change the name of the variable, because Counter
is the object callable name.
Also adding some "better" practice on your index.
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)
Upvotes: 3