本帖最后由 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)
复制代码
- open('b.txt', 'w').write(''.join(set(open('a.txt').readlines())))
复制代码 删除文件中的重复行并保持原来的顺序:- 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()
复制代码
- 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))
复制代码 看看各位大湿还有没有其它方法 |