【问题标题】:keeping count and storing of text instances保持文本实例的计数和存储
【发布时间】:2011-09-22 07:53:45
【问题描述】:

我想编写一个简单的代码,计算 txt 文件中最常出现的前三个行/文本,然后将该行/文本保存到另一个文本文件(这反过来将被读入 AutoCAD 的变量系统)。

忘记了我可以管理的 AutoCAD 部分我如何在 VB.net 中将 3 个最经常出现的文本行分别保存到自己的文本文件中,请参见下面的示例:

要读取的文本文件如下:

APG 比特币 VTS VTS VTS VTS 比特币 比特币 APG PNG

VB.net 程序然后将文本 VTS 保存到 mostused.txt BTR 到 2ndmostused.txt 和 APG 到 3rdmostused.txt

如何才能最好地实现这一目标?

【问题讨论】:

    标签: vb.net text count text-files readline


    【解决方案1】:

    由于我是 C# 开发人员,所以我会使用它:

    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);
    }
    

    【讨论】:

    • 我认为他不想要一行中的单词,只是行,这使得它更加简单:将整行添加到 dict
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多