如何从文件中删除重复的行?

30 python file-io text

我有一个包含一列的文件.如何删除文件中的重复行?

Vin*_*jip 61

在Unix/Linux上,uniq按照David Locke的回答使用命令,或者sort根据William Pursell的评论.

如果您需要Python脚本:

lines_seen = set() # holds lines already seen
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
    if line not in lines_seen: # not a duplicate
        outfile.write(line)
        lines_seen.add(line)
outfile.close()
Run Code Online (Sandbox Code Playgroud)

更新:sort/ uniq组合将删除重复,但返回与排序线,这可能会或可能不是你想要的是一个文件.上面的Python脚本不会重新排序行,但只删除重复项.当然,为了让上面的脚本也进行排序,只需outfile.write(line)在循环之后立即省略,而不是outfile.writelines(sorted(lines_seen)).

  • 此解决方案为+1.另一个增强可能是存储行的md5和,并比较当前行的md5总和.这应该会大大减少内存需求.(见http://docs.python.org/library/md5.html) (6认同)

Dav*_*cke 35

如果您使用的是*nix,请尝试运行以下命令:

sort <file name> | uniq
Run Code Online (Sandbox Code Playgroud)

  • 或者只是排序-u (11认同)

mar*_*ell 16

uniqlines = set(open('/tmp/foo').readlines())
Run Code Online (Sandbox Code Playgroud)

这将为您提供唯一线条列表.

将其写回某个文件就像下面这样简单:

bar = open('/tmp/bar', 'w').writelines(set(uniqlines))

bar.close()
Run Code Online (Sandbox Code Playgroud)

  • 线路没有排序的问题是什么?关于这里的问题...... (4认同)
  • 是的,但是根据它们如何散列,这些行将以某种随机顺序排列. (2认同)

MLS*_*LSC 6

你可以做:

import os
os.system("awk '!x[$0]++' /path/to/file > /path/to/rem-dups")
Run Code Online (Sandbox Code Playgroud)

在这里,您正在使用bash到python :)

您还有其他方法:

with open('/tmp/result.txt') as result:
        uniqlines = set(result.readlines())
        with open('/tmp/rmdup.txt', 'w') as rmdup:
            rmdup.writelines(set(uniqlines))
Run Code Online (Sandbox Code Playgroud)


Art*_*r M 6

它的重点已经在这里说过了 - 我在这里使用的是什么.

import optparse

def removeDups(inputfile, outputfile):
        lines=open(inputfile, 'r').readlines()
        lines_set = set(lines)
        out=open(outputfile, 'w')
        for line in lines_set:
                out.write(line)

def main():
        parser = optparse.OptionParser('usage %prog ' +\
                        '-i <inputfile> -o <outputfile>')
        parser.add_option('-i', dest='inputfile', type='string',
                        help='specify your input file')
        parser.add_option('-o', dest='outputfile', type='string',
                        help='specify your output file')
        (options, args) = parser.parse_args()
        inputfile = options.inputfile
        outputfile = options.outputfile
        if (inputfile == None) or (outputfile == None):
                print parser.usage
                exit(1)
        else:
                removeDups(inputfile, outputfile)

if __name__ == '__main__':
        main()
Run Code Online (Sandbox Code Playgroud)


sha*_*pan 5

获取列表中的所有行并制作一组行,您就完成了。例如,

>>> x = ["line1","line2","line3","line2","line1"]
>>> list(set(x))
['line3', 'line2', 'line1']
>>>
Run Code Online (Sandbox Code Playgroud)

如果您需要保留行的顺序 - 因为 set 是无序集合 - 试试这个:

y = []
for l in x:
    if l not in y:
        y.append(l)
Run Code Online (Sandbox Code Playgroud)

并将内容写回文件。

  • 是的,但这些行将根据它们的散列方式以某种随机顺序排列。 (3认同)