开发者

keeping count and storing of text instances

I would like to make a simple code that counts the top three most recurring lines/ text in a txt file then saves that line/ text to another text file (this in turn will be read into AutoCAD’s variable system).

Forgetting the AutoCAD part which I can 开发者_开发技巧manage how do I in VB.net save the 3 most recurring lines of text each to its own text file see example below:

Text file to be read reads as follows:

APG BTR VTS VTS VTS VTS BTR BTR APG PNG

The VB.net program would then save the text VTS to mostused.txt BTR to 2ndmostused.txt and APG to 3rdmostused.txt

How can this be best achieved?


Since I'm C# developer, I'll use it:

var dict = new Dictionary<string, int>();
using(var sr = new StreamReader(file))
{
   var line = string.Empty;
   while ((line = sr.ReadLine()) != null) 
   {
     var words = line.Split(' '); // get the words
     foreach(var word in words)
     {
       if(!dict.Contains(word)) dict.Add(word, 0);
       dict[word]++; // count them
     }
   }
}

var query = from d in dict select d order by d.Value; // now you have it sorted
int counter = 1;
foreach(var pair in query)
{
   using(var sw = new StreamWriter("file" + counter + ".txt"))
     sw.writer(pair.Key);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜