【问题标题】:UnboundLocalError: local variable 'Counter' referenced before assignmentUnboundLocalError:分配前引用的局部变量“Counter”
【发布时间】:2019-01-24 03:12:53
【问题描述】:

这是我的代码

    #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()

然后在运行上面的代码我得到错误

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

上面的代码有什么错误?

【问题讨论】:

  • 你会把Counter = Counter(split_it)改成counter = Counter(split_it),同时把Counter.most_common(10)改成counter.most_common(10)

标签: python string file


【解决方案1】:

您正在用变量覆盖导入的 Counter 类。 只需写例如counter = Counter(split_it),它应该可以工作。

顺便说一句,您可能想阅读 Python 的 PEP8 样式指南,通常您不使用以大写字母开头的变量名。

【讨论】:

    【解决方案2】:

    这应该可行:

    # 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()
    

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2020-01-16
      • 2019-12-05
      • 2017-09-19
      • 2020-09-26
      • 2022-01-02
      • 2019-03-22
      • 2021-07-01
      • 2021-10-16
      相关资源
      最近更新 更多