1

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)

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that go it working perfecting with multiple documents. Appreciate it.
2

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.

1 Comment

Thanks for the clarification!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.