实例:需要用Python删除文本文件a.txt中的重复行.
Case1:仅需要删除文件中的重复行:
rFile = open('a.txt', 'r')
wFile = open('b.txt', 'w')
allLine = rFile.readlines()
rFile.close()
s = set()
for i in allLine:s.add(i)
for i in s:wFile.write(i)
open('b.txt', 'w').write(''.join(set(open('a.txt').readlines())))
Case2:删除文件中的重复行并保持原来的顺序:
rFile = open("a.txt", "r")
wFile = open("b.txt", "w")
allLine = rFile.readlines()
rFile.close()
h = {}
for i in allLine:if not h.has_key(i):h[i]=1wFile.write(i)
wFile.close()
lines, sorted = open('a.txt', 'r').readlines(), lambda a, cmp: a.sort(cmp=cmp) or a
open('b.txt', 'w').write(''.join([i[0] for i in sorted([(j, lines.index(j)) for j in set(lines)], lambda a,b: a[1]-b[1] )]))
h,r,w ={}, file('a.txt'), file('b.txt','w')
w.write(reduce(lambda x,y:x+y, [i for i in r if h.get(i)==None and h.setdefault(i, True)]))
s = []
[ s.append(k) for k in open('a.txt') if k not in s ]
open('b.txt', 'w').write(''.join(s))
上述两种方法均可以实现删除重复行的目的,感兴趣的可以再考虑其他方法。