<大文本文件1>使用File.ReadLine

时间:2017-07-07 12:32:26

标签: c# file.readalllines

我是C#和面向对象编程的新手。我有一个解析一个非常大的文本文件的应用程序。

我有两本词典:

Dictionary<string, string> parsingDict //key: original value, value: replacement Dictionary<int, string> Frequency // key: count, value: counted string

我找到了每个键的频率。我能够获得所需的输出:

  

System1已被MachineA 5次取代

     

System2已被MachineB 7 time替换

     

System3已被MachineC 10次取代

     

System4已被MachineD 19次取代

以下是我的代码:

String[] arrayofLine = File.ReadAllLines(File);
           foreach (var replacement in parsingDict.Keys)
        {
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                if (arrayofLine[i].Contains(replacement))
                {
                    countr++;

                    Frequency.Add(countr, Convert.ToString(replacement));
                }
            }

        }


        Frequency = Frequency.GroupBy(s => s.Value)
                .Select(g => g.First())
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);  //Get only the distinct records.

        foreach (var freq in Frequency)
        {
            sbFreq.AppendLine(string.Format("The text {0} was replaced {2} time(s) with {1} \n",
            freq.Value, parsingDict[freq.Value],
            arrayofLine.Where(x => x.Contains(freq.Value)).Count())); 
        }

使用String[] arrayofLine = File.ReadAllLines(File);可以提高内存利用率。

arrayofLine.Where(x =&gt; x.Contains(freq.Value))。Count())如何使用File.ReadLine实现,因为它对内存友好。

2 个答案:

答案 0 :(得分:0)

您可以轻松地一次阅读一行(ref)。

相关代码如下所示:

Dictionary<string,int> lineCount = new Dictionary<string,int>();
string line;

// Read the file and display it line by line.
using(System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt"))
{
   while((line = file.ReadLine()) != null)
   {
      string value = DiscoverFreq(line);
      lineCount[value] += 1;
    }
}

注意:您必须考虑要存储的其他信息。将大文件中的行添加到字符串中与一次读取整个文件基本相同,但垃圾收集更多。

注2:我简化了更新计数的部分。您必须检查计数条目是否存在并添加它,如果存在则增加它。或者,您可以在扫描文件之前将所有freq.Values设置为0来初始化lineCounts。

如果唯一字的数量足够高,那么您可能需要使用像SQLite这样的小型数据库来存储计数。这使您可以快速查询信息,而无需考虑如何存储和读取您自己编写的自定义文件。

答案 1 :(得分:0)

string line = string.Empty;
Dictionary<string, int> found = new Dictionary<int, string>();
using(System.IO.StreamReader file = new System.IO.StreamReader(@"c:\Path\To\BigFile.txt"))
{
   while(!file.EndOfStream)
   {
      line = file.ReadLine();
      // Matches found logic
      if (!found.ContainsKey(line)) found.Add(line, 1);
      else found[line] = found[line] + 1;
    }
}
相关问题