【问题标题】:Remove Duplicate Lines From Text File?从文本文件中删除重复行?
【发布时间】:2010-11-17 17:54:18
【问题描述】:

给定一个文本行的输入文件,我希望识别和删除重复的行。请展示一个简单的 C# sn-p 来完成此操作。

【问题讨论】:

  • 有多种方法,有些方法比其他方法更容易实现。要采取的方法可能取决于文本文件的大小和预期的匹配行数。您能描述一下您要解决的具体问题吗?谢谢:)
  • 。 . .以及所需的性能。

标签: c# duplicates


【解决方案1】:

对于小文件:

string[] lines = File.ReadAllLines("filename.txt");
File.WriteAllLines("filename.txt", lines.Distinct().ToArray());

【讨论】:

  • 看起来 Distinct 使用了一个内部 Set 类,它似乎是一个简化的 HashSet 类。提供的“线条”不是很大 w.r.t。内存这应该表现得很好。
【解决方案2】:

这应该可以(并且会复制大文件)。

注意它只删除重复的连续行,即

a
b
b
c
b
d

最终会变成

a
b
c
b
d

如果您不想在任何地方重复,则需要保留一组您已经看过的行。

using System;
using System.IO;

class DeDuper
{
    static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Console.WriteLine("Usage: DeDuper <input file> <output file>");
            return;
        }
        using (TextReader reader = File.OpenText(args[0]))
        using (TextWriter writer = File.CreateText(args[1]))
        {
            string currentLine;
            string lastLine = null;

            while ((currentLine = reader.ReadLine()) != null)
            {
                if (currentLine != lastLine)
                {
                    writer.WriteLine(currentLine);
                    lastLine = currentLine;
                }
            }
        }
    }
}

请注意,这假定Encoding.UTF8,并且您要使用文件。不过,它很容易概括为一种方法:

static void CopyLinesRemovingConsecutiveDupes
    (TextReader reader, TextWriter writer)
{
    string currentLine;
    string lastLine = null;

    while ((currentLine = reader.ReadLine()) != null)
    {
        if (currentLine != lastLine)
        {
            writer.WriteLine(currentLine);
            lastLine = currentLine;
        }
    }
}

(请注意,这不会关闭任何东西 - 调用者应该这样做。)

以下版本将删除所有个重复项,而不仅仅是连续的:

static void CopyLinesRemovingAllDupes(TextReader reader, TextWriter writer)
{
    string currentLine;
    HashSet<string> previousLines = new HashSet<string>();

    while ((currentLine = reader.ReadLine()) != null)
    {
        // Add returns true if it was actually added,
        // false if it was already there
        if (previousLines.Add(currentLine))
        {
            writer.WriteLine(currentLine);
        }
    }
}

【讨论】:

    【解决方案3】:

    对于一个长文件(和非连续重复),我会逐行复制文件,构建一个哈希//位置查找表。

    复制每一行时检查散列值,如果发生冲突,请仔细检查该行是否相同并移至下一行。 (

    不过,只有相当大的文件才值得。

    【讨论】:

      【解决方案4】:

      这是一种流式处理方法,与将所有唯一字符串读入内存相比,它产生的开销应该更少。

          var sr = new StreamReader(File.OpenRead(@"C:\Temp\in.txt"));
          var sw = new StreamWriter(File.OpenWrite(@"C:\Temp\out.txt"));
          var lines = new HashSet<int>();
          while (!sr.EndOfStream)
          {
              string line = sr.ReadLine();
              int hc = line.GetHashCode();
              if(lines.Contains(hc))
                  continue;
      
              lines.Add(hc);
              sw.WriteLine(line);
          }
          sw.Flush();
          sw.Close();
          sr.Close();
      

      【讨论】:

      • 它需要更少的内存,但如果发生哈希冲突,它也会产生不正确的输出。
      【解决方案5】:

      我是 .net 的新手,写了一些更简单的东西,可能效率不高。请随意填写以分享您的想法。

      class Program
      {
          static void Main(string[] args)
          {
              string[] emp_names = File.ReadAllLines("D:\\Employee Names.txt");
              List<string> newemp1 = new List<string>();
      
              for (int i = 0; i < emp_names.Length; i++)
              {
                  newemp1.Add(emp_names[i]);  //passing data to newemp1 from emp_names
              }
      
              for (int i = 0; i < emp_names.Length; i++)
              {
                  List<string> temp = new List<string>();
                  int duplicate_count = 0;
      
                  for (int j = newemp1.Count - 1; j >= 0; j--)
                  {
                      if (emp_names[i] != newemp1[j])  //checking for duplicate records
                          temp.Add(newemp1[j]);
                      else
                      {
                          duplicate_count++;
                          if (duplicate_count == 1)
                              temp.Add(emp_names[i]);
                      }
                  }
                  newemp1 = temp;
              }
              string[] newemp = newemp1.ToArray();  //assigning into a string array
              Array.Sort(newemp);
              File.WriteAllLines("D:\\Employee Names.txt", newemp); //now writing the data to a text file
              Console.ReadLine();
          }
      }
      

      【讨论】:

      • 一个想法:如果您可以评论您的代码以解释您在做什么(以及为什么),这将很有用 - 这将帮助其他人理解您的方法并将其应用于他们未来的情况.
      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多