这是我的代码
#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
上面的代码有什么错误?
答案 0 :(得分:2)
您正在用变量覆盖导入的Counter类。
仅写例如[ {"id":1, "text":"sample", "date":"whateverformat i want i.e YY-MM-DD","current_user_likes":"true/false"} ........]
,它应该可以工作。
顺便说一句,您可能想阅读《 PEP8 Python样式指南》,通常您不使用以大写字母开头的变量名称。
答案 1 :(得分:0)
这应该有效:
# 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()