从文本文件中删除重复行?

11

假设有一个文本文件,其中包含多行文本,我希望能够识别并移除重复的行。请提供一段简单的 C# 代码片段来完成这个任务。


有各种方法可供选择,其中一些比其他方法更容易实现。采取的方法可能取决于文本文件的大小和预期匹配行数。您能描述一下您要解决的具体问题吗?谢谢 :) - Binary Worrier
...和所期望的性能。 - Binary Worrier
5个回答

40

对于小文件:

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

看起来Distinct使用了一个内部的Set类,这个类似乎是一个简化版的HashSet类。只要'lines'相对于内存不是太大,这个方法应该会非常高效。 - user7116

22

这应该可以(并且可以处理大文件)。

请注意,它仅会移除重复的连续行,也就是说。

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
这里提供了一种流式处理方法,相较将所有独特的字符串都读入内存,它所需的开销更小。
    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();

1
它需要更少的内存,但如果存在哈希冲突,它也会产生不正确的输出。 - Robert Rossney

3
对于长文件(且非连续重复项),我会逐行复制文件并构建哈希//位置查找表。
在复制每一行时,请检查哈希值,如果有冲突,请再次检查该行是否相同,并移动到下一行。
但仅对较大的文件才值得这样做。

1

我是.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();
    }
}

一个想法:如果你能注释你的代码来解释你正在做什么(以及为什么),那将会有所帮助 - 这将有助于其他人理解你的方法并将其应用到他们未来的情况中。 - Wai Ha Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接