ss321c
ss321c

Reputation: 799

UnboundLocalError: local variable 'Counter' referenced before assignment

Here is my code

    #word count2
from collections import Counter
def main():
    with open("search words.txt","r") as myfile:
         data=myfile.read()
         topTenWords(data)


def topTenWords(wordCountDict):
    split_it=wordCountDict.split()
    Counter = Counter(split_it)
    most_common=Counter.most_common(10)
    print(most_common)

if __name__=='__main__':
  main()

then upon running the above code I am getting error

word count2.py 
Traceback (most recent call last):
  File "D:/word count2.py", line 16, in <module>
    main()
  File "D:/word count2.py", line 6, in main
    topTenWords(data)
  File "D:/word count2.py", line 11, in topTenWords
    Counter = Counter(split_it)
UnboundLocalError: local variable 'Counter' referenced before assignment

What is the mistake in above code?

Upvotes: 0

Views: 543

Answers (2)

Yule Augustine
Yule Augustine

Reputation: 34

this should works:

# coding:utf-8
from collections import Counter


def main():
    with open("../docs/words.txt", "r") as myfile:
        data = myfile.read()
        topTenWords(data)
def topTenWords(wordCountDict):
    split_it = wordCountDict.split()
    counter = Counter(split_it)
    most_common = counter.most_common(10)
    print(most_common)


if __name__ == '__main__':
    main()

Upvotes: 0

Bernhard
Bernhard

Reputation: 1273

You are overwriting the imported Counter Class with a variable. Just write for example counter = Counter(split_it) and it should work.

Also just btw, you might wanna read the PEP8 Style Guide for Python, usually you don't use variable names that start with capital letters.

Upvotes: 2

Related Questions