我有一个包含大约1200行的文本文件,其中一些是重复的。
我该如何找到文件中的重复行(不考虑大小写),并将其文本打印在屏幕上,以便我可以找到它们?我不想删除它们或做任何其他操作,只是想找到可能存在的重复行。
我有一个包含大约1200行的文本文件,其中一些是重复的。
我该如何找到文件中的重复行(不考虑大小写),并将其文本打印在屏幕上,以便我可以找到它们?我不想删除它们或做任何其他操作,只是想找到可能存在的重复行。
使用set非常简单:
with open('file') as f:
seen = set()
for line in f:
line_lower = line.lower()
if line_lower in seen:
print(line)
else:
seen.add(line_lower)
file
对象是迭代器。您可以直接对它们进行迭代。 :) -- 如果你问我,那真是一个很酷的设计决定。 - mgilsonif line_lower in seen and line_lower.strip():
。或者在for语句的第一行添加if not line.strip(): continue
。 - Steven Rumbalski由于只有1200行代码,因此您也可以使用collections.Counter()
:
>>> from collections import Counter
>>> with open('data1.txt') as f:
... c=Counter(c.strip().lower() for c in f if c.strip()) #for case-insensitive search
... for line in c:
... if c[line]>1:
... print line
...
data1.txt
的内容如下:ABC
abc
aBc
CAB
caB
bca
BcA
acb
输出结果为:
cab
abc
bca
这种方法无法提供行号,但是可以给出一个重复行的列表,您可以进一步进行调查。例如:
tr 'A-Z' 'a-z' < /tmp/foo | sort | uniq -d
# /tmp/foo
one
One
oNe
two
three
上面列出的管道将正确产生:
一个
然后可以使用grep查找相关的行号,例如:
grep --ignore-case --line-number one /tmp/foo