Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从文件中删除重复行?_Python_Text_File Io - Fatal编程技术网

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

Python 如何从文件中删除重复行?,python,text,file-io,Python,Text,File Io,我有一个只有一列的文件。如何删除文件中的重复行?如果打开*nix,请尝试运行以下命令: sort <file name> | uniq sort | uniq 在Unix/Linux上,根据David Locke的回答使用uniq命令,或者根据William Pursell的评论使用sort 如果需要Python脚本: lines_seen = set() # holds lines already seen outfile = open(outfilename, "w") for

我有一个只有一列的文件。如何删除文件中的重复行?

如果打开*nix,请尝试运行以下命令:

sort <file name> | uniq
sort | uniq

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

如果需要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()
更新:排序/
uniq
组合将删除重复项,但返回一个已排序行的文件,这可能是您想要的,也可能不是您想要的。上面的Python脚本不会对行重新排序,只会删除重复的行。当然,要让上面的脚本也进行排序,只需省去
outfile.write(line)
,而是在循环之后立即执行
outfile.writeline(sorted(line_seen))

这将为您提供唯一行的列表

将其写回某个文件将非常简单:

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

bar.close()

把你的所有行都列在列表中,然后做一组行,你就完成了。 比如说,

>>> x = ["line1","line2","line3","line2","line1"]
>>> list(set(x))
['line3', 'line2', 'line1']
>>>
然后将内容写回文件。

这是我的解决方案

if __name__ == '__main__':
f = open('temp.txt','w+')
flag = False
with open('file.txt') as fp:
    for line in fp:
        for temp in f:
            if temp == line:
                flag = True
                print('Found Match')
                break
        if flag == False:
            f.write(line)
        elif flag == True:
            flag = False
        f.seek(0)
    f.close()

Python一行程序:

python -c "import sys; lines = sys.stdin.readlines(); print ''.join(sorted(set(lines)))" < InputFile > OutputFile
python-c“导入sys;lines=sys.stdin.readlines();打印“”。连接(已排序(设置(行))”OutputFile
您可以执行以下操作:

import os
os.system("awk '!x[$0]++' /path/to/file > /path/to/rem-dups")
在这里,您将使用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))

这是对这里已经说过的话的重复——这里是我所用的

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()
导入optpass
def removeDups(输入文件、输出文件):
lines=open(输入文件'r')。readlines()
行集合=集合(行)
输出=打开(输出文件“w”)
对于“行中的行”\u集:
输出。写入(行)
def main():
parser=optparse.OptionParser('usage%prog'+\
“-i-o”)
parser.add_选项('-i',dest='inputfile',type='string',
help='指定您的输入文件')
parser.add_选项('-o',dest='outputfile',type='string',
help='指定输出文件')
(options,args)=parser.parse_args()
inputfile=options.inputfile
outputfile=options.outputfile
如果(inputfile==None)或(outputfile==None):
打印语法分析器.用法
出口(1)
其他:
移除UPS(输入文件、输出文件)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()

添加到@David Locke的答案中,使用*nix系统,您可以运行

sort -u messy_file.txt > clean_file.txt

它将创建
clean_file.txt
按字母顺序删除重复项。

如果有人正在寻找一种使用散列且更华丽的解决方案,这就是我目前使用的:

def remove_duplicate_lines(input_path, output_path):

    if os.path.isfile(output_path):
        raise OSError('File at {} (output file location) exists.'.format(output_path))

    with open(input_path, 'r') as input_file, open(output_path, 'w') as output_file:
        seen_lines = set()

        def add_line(line):
            seen_lines.add(line)
            return line

        output_file.writelines((add_line(line) for line in input_file
                                if line not in seen_lines))
看看我为从文本文件中删除重复电子邮件而创建的脚本。希望这有帮助


在同一个文件中编辑它

lines_seen = set() # holds lines already seen

with open("file.txt", "r+") as f:
    d = f.readlines()
    f.seek(0)
    for i in d:
        if i not in lines_seen:
            f.write(i)
            lines_seen.add(i)
    f.truncate()
通俗易懂

以open('sample.txt')作为fl的
:
content=fl.read().split('\n')
内容=设置([line for line in content if line!=''))
内容='\n'。加入(内容)
以open('sample.txt','w')作为fl:
外语书面语(内容)
cat|grep'^[a-zA-Z]+$'| sort-u>outfile.txt

要从文件中筛选和删除重复值。

在运行uniq之前,您需要运行sort,因为uniq只会删除与前一行相同的行。是的-我参考了您的答案,但没有重申此解决方案的排序顺序是uniq.+1。一个进一步的增强可能是存储行的md5和,并比较当前行的md5和。这将大大减少内存需求。(见)+1我本可以自己写这段代码,但为什么要在谷歌上写:)这个答案给出
回溯(最后一次调用):文件“sort and unique.py”,第5行,在outfile中。写(line)MemoryError
如何解决它,但是,根据行的散列方式,这些行将以某种随机顺序排列。此代码的问题是,在编写之后,最后一行没有“\n”。然后输出结果将有一行与合并的两行。您的解决方案适用于较小的文件。其中文件大小高达300mb或400mb。除此之外。是的,但行将根据其散列方式以某种随机顺序排列。当您可以只添加行本身时,将行的散列添加到集合中有什么意义?这将删除重复项,但会修改(排序)行的顺序。不完全是所要求的。最好使用open context manager来打开文件,以便安全地关闭它。如果文件很大,一次读取整个文件可能不起作用。
# function to remove duplicate emails
def remove_duplicate():
    # opens emails.txt in r mode as one long string and assigns to var
    emails = open('emails.txt', 'r').read()
    # .split() removes excess whitespaces from str, return str as list
    emails = emails.split()
    # empty list to store non-duplicate e-mails
    clean_list = []
    # for loop to append non-duplicate emails to clean list
    for email in emails:
        if email not in clean_list:
            clean_list.append(email)
    return clean_list
    # close emails.txt file
    emails.close()
# assigns no_duplicate_emails.txt to variable below
no_duplicate_emails = open('no_duplicate_emails.txt', 'w')

# function to convert clean_list 'list' elements in to strings
for email in remove_duplicate():
    # .strip() method to remove commas
    email = email.strip(',')
    no_duplicate_emails.write(f"E-mail: {email}\n")
# close no_duplicate_emails.txt file
no_duplicate_emails.close()
lines_seen = set() # holds lines already seen

with open("file.txt", "r+") as f:
    d = f.readlines()
    f.seek(0)
    for i in d:
        if i not in lines_seen:
            f.write(i)
            lines_seen.add(i)
    f.truncate()
cat <filename> | grep '^[a-zA-Z]+$' | sort -u > outfile.txt