返回列表 发帖

[技术讨论] Python脚本删除文件中的重复行

本帖最后由 Python 于 2012-4-3 19:59 编辑

删除文件中的重复行:
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)COPY
open('b.txt', 'w').write(''.join(set(open('a.txt').readlines())))COPY
删除文件中的重复行并保持原来的顺序:
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]=1
        wFile.write(i)
wFile.close()COPY
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] )]))COPY
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)]))COPY
s = []
[ s.append(k) for k in open('a.txt') if k not in s ]
open('b.txt', 'w').write(''.join(s))COPY
看看各位大湿还有没有其它方法

本帖最后由 ivor 于 2012-4-3 17:02 编辑

办法都让你写出来了

第一个例子,python3.2版本运行需更改为
rFile.close()COPY

TOP

回复 2# ivor


嗯,更新了一下顶楼的代码,省的后面再有人提这茬

TOP

返回列表