Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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 在转换为CSV之前删除文本文件中的重复项_Python_File_Csv - Fatal编程技术网

Python 在转换为CSV之前删除文本文件中的重复项

Python 在转换为CSV之前删除文本文件中的重复项,python,file,csv,Python,File,Csv,我希望在我拥有的原始文本文件中识别重复项,一旦识别出重复项,我希望在创建新的CSV文件时忽略它 raw_file_reader = csv.DictReader(open(raw_file), delimiter='|') 保留在我的原始文件是一个简单的.txt文件 with open('file') as f: seen = set() for line in f: line_lower = line.lower() if line_lower in seen

我希望在我拥有的原始文本文件中识别重复项,一旦识别出重复项,我希望在创建新的CSV文件时忽略它

raw_file_reader = csv.DictReader(open(raw_file), delimiter='|')
保留在我的原始文件是一个简单的.txt文件

with open('file') as f:
  seen = set()
  for line in f:
      line_lower = line.lower()
      if line_lower in seen:
          print(line)
      else:
          seen.add(line_lower)
我可以使用集合找到重复项

for row in raw_file_reader:
            if ('Symbol' in row):
                symbol = row['Symbol']
            elif ('SYMBOL' in row):
                symbol = row['SYMBOL']
            else:
                raise exception

            if symbol not in symbol_lookup:
                continue

我只是不知道如何在转换到csv文件之前忽略重复项。

我会使用
csv
库来完成这项工作。此外,还有一种内置的方法来枚举项。所以,让我们使用它

import csv
with open("in.txt","r") as fi, open("out.csv","w") as fo:
    writer = csv.writer(fo, lineterminator='\n')
    writer.writerows(enumerate(set(fi.read().split("|"))))

您可以通过将所有条目存储在一个集合中来删除重复项,如下所示:

import csv

seen = set()
output = []

source_file = "file.csv"

with open(source_file, 'rb') as f_input:
    csv_input = csv.reader(f_input, delimiter='|')

    for row in csv_input:
        if tuple(row) not in seen:
            output.append(row)
            seen.add(tuple(row))

with open(source_file, 'wb') as f_output:        
    csv_output = csv.writer(f_output)
    csv_output.writerows(output)
给您一个输出文件:

20100830,TECD,15004300,N
20100830,技术,100100,N
2010年8月30日,北卡罗来纳州特库,100391
20100830,TEF,13001300,N
20100830,TEG,9001900,北
其工作原理是将每一整行转换为一个元组,然后将其存储为一个集合。这使得对重复行的测试变得简单


在Python 2.7.12上测试,您可以简单地创建一个自定义迭代器,该迭代器将返回原始文件行并删除重复项:

class Dedup:
    def __init__(self, fd):
        self.fd = fd       # store the original file object
        self.seen = set()  # initialize an empty set for lines
    def __next__(self):        # the iterator method
        while True:
            line = next(self.fd)
            if not line in self.seen:
                self.seen.add(line)
                return line
            # print("DUP>", line.strip(), "<") # uncomment for tests
    def __iter__(self):        # make the iterator compatible Python 2 and 3
        return self
    def next(self):
        return self.__next__()
    def __enter__(self):       # make it a context manager supporting with
        return self
    def __exit__(self, typ, value, traceback):
        self.fd.close()        # cleanup

但要当心!这将要求所有行都存储在集合中,这意味着原始文件必须适合内存。

如果您包含原始文本文件的样本,并显示您希望输出的外观,这将有所帮助。@MartinEvans添加了样本请不要破坏您的帖子。一旦你发布了一个问题,它就属于Stack Overflow社区(在CC by SA许可证下)。如果您想解除此帖子与您的帐户的关联,请参阅我已经想到了这一点,但是我不想完全创建一个新的csv文件,我只是不想将副本传输到csv文件。对于小文件,您可以将其读取到内存中,然后覆盖该文件。或者在完成后删除并重命名。我将更新它以覆盖您的输入文件。我还添加了处理.txt后当前csv输出的外观。
with Dedup(open(raw_file)) as fd:
   reader = csv.DictReader(fd, delimiter='|')
   for row in reader:
        # process each now unique row...