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

给定文本行的输入文件,我想要识别和删除重复的行。 请显示一个简单的C#片段来完成此操作。

这应该做(并将与大文件一起复制)。

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

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  "); 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 previousLines = new HashSet(); 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); } } } 

对于小文件:

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

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

复制每一行时检查散列值,如果有碰撞,请检查该行是否相同并移动到下一行。 (

但是,对于相当大的文件,它只值得。

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

  var sr = new StreamReader(File.OpenRead(@"C:\Temp\in.txt")); var sw = new StreamWriter(File.OpenWrite(@"C:\Temp\out.txt")); var lines = new HashSet(); 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(); 

我是.net的新手,写的更简单,可能效率不高。请免费填写分享您的想法。

 class Program { static void Main(string[] args) { string[] emp_names = File.ReadAllLines("D:\\Employee Names.txt"); List newemp1 = new List(); 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 temp = new List(); 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(); } }