我有一个 Python 脚本,我试图用它来打印 Duplicate.txt 文件中的重复数字:
newList = set()
datafile = open ("Duplicate.txt", "r")
for i in datafile:
if datafile.count(i) >= 2:
newList.add(i)
datafile.close()
print(list(newList))
我收到以下错误,请问有人能帮忙吗?
AttributeError: '_io.TextIOWrapper' 对象没有属性 'count'
请您参考如下方法:
问题正如它所说:文件对象不知道如何计算任何东西。它们只是迭代器,而不是列表或字符串或类似的东西。
部分原因是这样一遍又一遍地扫描整个文件可能会非常慢。
如果你真的需要使用count,你可以先把这些行放到一个列表中。列表完全在内存中,因此一遍又一遍地扫描它们并没有那么慢,而且它们有一个 count 方法可以完全按照您的意愿进行操作:
datafile = open ("Duplicate.txt", "r")
lines = list(datafile)
for i in lines:
if lines.count(i) >= 2:
newList.add(i)
datafile.close()
但是,有一个更好的解决方案:边走边记数,然后记下大于等于 2 的数。实际上,您可以将其写成两行:
counts = collections.Counter(datafile)
newList = {line for line, count in counts.items() if count >= 2}
但是如果您不清楚为什么这样做,您可能想要更明确地做到这一点:
counts = collections.Counter()
for i in datafile:
counts[i] += 1
newList = set()
for line, count in counts.items():
if count >= 2:
newList.add(line)
或者,如果您甚至不了解 Counter 的基础知识:
counts = {}
for i in datafile:
if i not in counts:
counts[i] = 1
else:
counts[i] += 1
