簡體   English   中英

計算列表中字符串的出現次數並將其顯示在控制台中

[英]Count occurence of a string in a list and display it in console

我現在正在創建一個 Logparser,我可以逐行處理文件夾中的所有文件並提取我想要的子字符串,它是"fct="之后的值。 所有這些都使用Regex ,我將結果放在List 現在我想Count列表中每個字符串的出現次數並顯示它。

我正在使用 GroupBy 但是當我顯示結果時,所有出現都在1

實際的:

 720 1x
 720 1x
 710 1x

它應該是:

 720 2x
 710 1x  

我能夠發現問題在於我逐行讀取我的文件,因此如果"fct="值不是在同一行上兩次,它不會將其計數為2而是僅將其計數為1出現的每一行.

所以我需要找到一種方法來計算我的列表,而不是逐行計算我的文件。

我真的是初學者,所以不知道如何做到這一點,任何提示將不勝感激。

這是日志數據示例:

<dat>FCT=10019,XN=KEY,CN=ROHWEPJQSKAUMDUC</dat></logurl>
<dat>XN=KEY,CN=RTU FCT=4515</dat>LBZ=test.sqi</logurl>
<dat>XN=KEY,CN=RT</dat>FCT=10019</logurl>

我想顯示:

 FCT=10019 2x
 FCT=4515 1x

我的代碼:

   class Program
{

    static void Main(string[] args)
    {

        int counter = 0;
        string[] dirs = Directory.GetFiles(@"C:/LogParser/LogParserV1", "*.txt");
        StreamWriter sw = new StreamWriter("C:/LogParser/LogParserV1/test.txt");      
        char[] delimiters = { '<', ',', '&', ':', ' ', '\\', '\'' };
        string patternfct = "(?<=FCT=)[0-9]*";


        foreach (string fileName in dirs)
        {
            StreamReader sr = new StreamReader(fileName);

            {
                String lineRead;
                while ((lineRead = sr.ReadLine()) != null)
                {

                    //To find all the value of fct= occurence 
                    var listfct = Regex.Matches(lineRead, patternfct, 
  RegexOptions.IgnoreCase).Cast<Match>().Select(x => x.Value).ToList();


                   var fctGroups = listfct.GroupBy(i => i);
                    foreach (var grp in fctGroups)
                    {
                        var fct = grp.Key;
                        var total = grp.Count();
                        System.Console.WriteLine("fct=" + fct + " " + "Total=" + total);
                    }

                    counter++;
                }
                System.Console.WriteLine(fileName);

                sr.Close();
                sw.Close();
            }
        }

        // Suspend the screen.  
        System.Console.ReadLine();

    }
}
}

您可以嘗試借助 Linq 查詢數據:

using System.Linq;
using System.Text.RegularExpressions;

...

Regex regex = new Regex("(?<=FCT=)[0-9]*", RegexOptions.IgnoreCase);

var records = Directory
  .EnumerateFiles(@"C:/LogParser/LogParserV1", "*.txt")
  .SelectMany(file => File.ReadLines(file))
  .SelectMany(line => regex
     .Matches(line)
     .Cast<Match>()
     .Select(match => match.Value))
  .GroupBy(number => number)
  .Select(group => $"FCT={group.Key} {group.Count()}x");

foreach (string record in records)
  Console.WriteLine(record);

演示:我們不能模仿目錄和文件,所以我已經刪除了

  Directory
    .EnumerateFiles(@"C:/LogParser/LogParserV1", "*.txt")
    .SelectMany(file => File.ReadLines(file))

但添加了testLines

  string[] testLines = new string[] {
    "<dat>FCT=10019,XN=KEY,CN=ROHWEPJQSKAUMDUC</dat></logurl>",
    "<dat>XN=KEY,CN=RTU FCT=4515</dat>LBZ=test.sqi</logurl>",
    "<dat>XN=KEY,CN=RT</dat>FCT=10019</logurl>",
  };

  Regex regex = new Regex("(?<=FCT=)[0-9]*", RegexOptions.IgnoreCase);

  var records = testLines
    .SelectMany(line => regex
       .Matches(line)
       .Cast<Match>()
       .Select(match => match.Value))
    .GroupBy(number => number)
    .Select(group => $"FCT={group.Key} {group.Count()}x");

  foreach (string record in records)
    Console.WriteLine(record);

結果:

FCT=10019 2x
FCT=4515 1x

編輯:如果要將file包含到records ,可以使用匿名對象:

var records = Directory
  .EnumerateFiles(@"C:/LogParser/LogParserV1", "*.txt")
  .SelectMany(file => File
     .ReadLines(file)
     .Select(line => new {
        file = file,
        line = line,  
      }))
  .SelectMany(item => regex
     .Matches(item.line)
     .Cast<Match>()
     .Select(match => new {
        file   = item.file,
        number = match.Value  
      }))
  .GroupBy(item => new {
     file   = item.file, 
     number = item.number
   })
  .OrderBy(group => group.Key.file)
  .ThenBy(group => group.Key.number)
  .Select(group => $"{group.Key.file} has FCT={group.Key.number} {group.Count()}x")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM