python - UnboundLocalError:分配前引用的局部变量“Counter”
问题描述
这是我的代码
#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 = Counter(split_it)
,它应该可以工作。
顺便说一句,您可能想阅读 Python 的 PEP8 样式指南,通常您不使用以大写字母开头的变量名。
推荐阅读
- visual-studio-code - VS Code 是否有扩展来替换标题栏?
- python - 请求错误:未找到连接适配器
- python - 如何使用与功能相关的颜色图绘制立方体或平行六面体
- python - 如何使用 django_oauth_toolkit 从 refresh_token 获取新的 access_token?
- filter - 标准外设库中的 STM8A CAN 过滤
- javascript - 点击html标签后Javascript不起作用?
- php - 刷新页面时如何自动清除缓存?
- azure - 接收双更新通知的 Azure IoT 设备
- excel - 查找包含波浪号的文本
- swift - 在 Swift 中使用重定向 url 时的 ATS 策略问题