我试图从一个文件中读取,程序遍历文本文件的每一行,比较每行的前8个字符,并将这些行连接成一个其中的8个字符是similar.See代码:
while ((line1 = fileread1.ReadLine()) != null)
{
line2 = fileread2.ReadLine();
while (line2 != null)
{
if (line1.Length >= 8 && line2.Length >= 8 &&
line1.Substring(0, 8) == line2.Substring(0, 8))
{
//line2 = line2.Remove(0, 60);
line1 = line1 +" "+ line2;
}
line2 = fileread3.ReadLine();
counter2++;
}
filewrite.WriteLine(line1);
counter1++;
}问题1:
如何获取fileread2的计数并将其赋值给fileread3,因为每次执行内部循环时,我都需要将fileread3的计数重置为与fileread2相同。
问题2:
如何将组合后的行写成前8个字符匹配的单行?
发布于 2014-05-14 17:50:05
通过阅读评论,我了解到您实际上想要删除重复项。或者,更具体地说,是以相同的8个字符开头的行。
如果是这样的话,为什么不使用键的集合来记住具有相同8个初始字符的字符串是否还没有加载。
例如,你可以有一个集合(如List),你可以在其中添加8字符子字符串。然后,在编写代码行之前,首先检查子字符串是否已经在集合中。如果它是,那么你知道它是一个副本,你不会写它。
另一种选择是,如果您想要计算有多少个特定类型的重复项,则可以使用字典。当你有一个特定类型的副本时,你可以在字典中增加计数器。
发布于 2014-05-14 18:05:45
如果您希望根据前8个字符对数据进行分组,则只需:
var groups = File.ReadLines(your_file_name).GroupBy(line => line.Substring(0, 8));对组中的元素调用Count()的元素进行计数
groups.First().Count()(您也可以通过foreach (var group in groups)通过groups枚举。)
分组结果将包含文件中的完整行。如果您不想在结果中包含"key“(即前8个字符),则可以使用GroupBy的重载
var groups = File.ReadLines(your_file_name).GroupBy(line => line.Substring(0, 8), line => line.Substring(8));为了获得包含"key“和连接的行的新输出,您可以使用如下代码:
var groups = File.ReadLines(input_file).GroupBy(line => line.Substring(0, 8), line => line.Substring(8));
File.WriteAllLines(output_file, groups.Select(group => string.Format("{0}{1}", group.Key, string.Join(string.Empty, group))));发布于 2014-05-14 18:43:39
因为你有很大的文件,所以File.ReadAllLines可能不适合你。您可以声明以下方法(我们需要使用Stream,因为StreamReader没有Position属性):
public static string ReadLine(Stream stream)
{
return ReadLine(stream, Encoding.UTF8);
}
public static string ReadLine(Stream stream, Encoding encoding)
{
List<byte> lineBytes = new List<byte>();
while (stream.Position < stream.Length)
{
byte b = (byte)stream.ReadByte();
if (b == 0x0a)
break;
if (b == 0x0d)
continue;
lineBytes.Add(b);
}
return encoding.GetString(lineBytes.ToArray());
}示例代码:
string sourceFileName = "input.txt";
string targetFileName = "output.txt";
using (StreamWriter targetWriter = new StreamWriter(targetFileName))
using (FileStream sourceStream = File.OpenRead(sourceFileName))
{
HashSet<string> processedKeys = new HashSet<string>();
while (sourceStream.Position < sourceStream.Length)
{
string line = ReadLine(sourceStream);
if (line.Length < 8)
targetWriter.WriteLine(line);
else
{
string key = line.Substring(0, 8);
if (processedKeys.Contains(key))
continue;
targetWriter.Write(line);
long backupPosition = sourceStream.Position;
while (sourceStream.Position < sourceStream.Length)
{
string dupLine = ReadLine(sourceStream);
if (dupLine.Length < 8)
continue;
string dupKey = dupLine.Substring(0, 8);
if (dupKey == key)
targetWriter.Write(" " + dupLine);
}
sourceStream.Position = backupPosition;
targetWriter.WriteLine();
processedKeys.Add(key);
}
}
}https://stackoverflow.com/questions/23647133
复制相似问题