Statistics.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System.Collections.Generic;
  2. using Newtonsoft.Json.Linq;
  3. using System.Linq;
  4. namespace analyzeJSON
  5. {
  6. public record WordCountResult<T>(T NodeCounts, int TotalWordCount);
  7. public class Statistics
  8. {
  9. private readonly Dictionary<string, int> nodeCounts = new();
  10. private int totalWordCount;
  11. private static int CountWords(string text)
  12. {
  13. var words = text.Split(new char[] { ' ', '\t', '\n' });
  14. return words.Count(x => !string.IsNullOrWhiteSpace(x));
  15. }
  16. public void RunStatistics(JToken token)
  17. {
  18. if (token.Type != JTokenType.String)
  19. return;
  20. var tokenName = AnalyzeJSON.GetNameFromPath(token.Path);
  21. if (!nodeCounts.ContainsKey(tokenName))
  22. nodeCounts.Add(tokenName, 0);
  23. var wordCount = CountWords(token.Value<string>());
  24. nodeCounts[tokenName] += wordCount;
  25. totalWordCount += wordCount;
  26. }
  27. public WordCountResult<Dictionary<string, int>> Result => new(nodeCounts, totalWordCount);
  28. }
  29. }