python - 在列表上调用 Counter 函数时出错
问题描述
我正在编写一个程序来计算 txt 文件中出现次数最多的 20 个单词。当我将其剥离并计数一个文件时,该程序运行良好,但是当我输入两个要剥离和计数的文件时,我收到一条错误消息,提示“'Counter' object is not callable”。我很困惑,因为这同样适用于一个文档。下面是我的代码,错误来自 while 循环。谢谢!
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)
解决方案
我不确定为什么它适用于 1 个元素,但是,您可以尝试更改变量的名称,因为Counter
是对象可调用名称。
还在您的索引上添加一些“更好”的做法。
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)
推荐阅读
- python - ModuleNotFoundError(适用于 bs4),当使用命令行运行在 PyCharm 上创建的 Python 程序时?
- android - 使用 POST 调用 Android 浏览器?
- javascript - 动态添加的下拉菜单不应用 jQuery
- checkbox - VBA Excel 如何创建不更改 ActiveWorkbook.Saved 状态的 CheckBox?
- python - 在 matplotlib 中绘制图形时遇到问题
- python - 将两个字典键值与 pandas 数据框行匹配
- python - 使用 Python 选择特定的 Excel 输入并将它们保存到另一个 Excel 文件中?
- kotlin - 以“多态”方式处理对象列表的正确方法
- github - 注册;合并请求github时发现冲突
- laravel - Laravel 合集展示与短刊