aboutsummarylogtreecommitdiffstats
path: root/sitestats.pas
blob: 794ad37a273ac394800e70d258ac8a303c36b295 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
{ Статистика продуктивности }
unit SiteStats;

{$mode ObjFPC}{$H+}

interface

uses
  Classes, SysUtils, RegExpr;

type
  { Класс для статистики текста }

  { TSiteStats }

  TSiteStats = class(TObject)
    { Очищает текст от тегов }
    function StripHTML(const HTML: String): String;
    { Подсчет числа слов в строке s }
    function CountWords(s: string): Integer;
    { Подсчет числа предложений в строке s}
    function CountSentences(s: string): Integer;
    { Подсчет числа символов в строке s}
    function CountNonSpaceChars(s: string): Integer;
    { Время на дочитывание }
    function TimeToReadingInMinutes(words_total : Integer) : Integer;
    { Подстановка статистики в текст }
    function ReplaceStats(s: string): String;
  end;

implementation

{ TSiteStats }

function TSiteStats.StripHTML(const HTML: String): String;
var
  RegEx: TRegExpr;
begin
  // Initialize the result with the input HTML string
  Result := HTML;

  // Create a new instance of TRegExpr for pattern matching
  RegEx := TRegExpr.Create;
  try
    // Define the regex pattern to match HTML tags
    RegEx.Expression := '<[^>]*>';

    // Replace all matches (HTML tags) with an empty string
    if RegEx.Exec(Result) then
      Result := RegEx.Replace(Result, '');

    // Optionally remove extra spaces caused by tag removal
    RegEx.Expression := '\s{2,}';
    if RegEx.Exec(Result) then
      Result := RegEx.Replace(Result, ' ');
  finally
    // Free the TRegExpr object
    RegEx.Free;
  end;

  // Trim the result to remove leading/trailing spaces
  Result := Trim(Result);
end;

function TSiteStats.CountWords(s: string): Integer;
var
  i, wordCount: Integer;
  inWord: Boolean;
begin
  wordCount := 0;
  i := 1;
  while (i <= Length(s)) do begin
    if (s[i] = ' ') or (s[i] = ',') or (s[i] = '.') or (s[i] = '?') or (s[i] = '!')
    or (s[i] = ':') or (s[i] = '-') then
       begin
            inWord := False;
            Inc(I);
            continue;
       end else
       begin
         if not inWord then Inc(wordCount);
         inWord:=True;
       end;
    Inc(i);
  end;
  Result := wordCount;
end;

function TSiteStats.CountSentences(s: string): Integer;
var
  i: Integer;
begin
  Result := 0;

  // Удаляем пробелы в начале и конце строки
  s := Trim(s);

  // Проверяем, есть ли в строке хотя бы один символ
  if Length(s) = 0 then
    Exit(0);

  // Считаем количество предложений
  for i := 1 to Length(s) do
  begin
    if s[i] in ['.', '!', '?'] then
      Inc(Result);
  end;

  // Если строка заканчивается на знак препинания, добавляем одно предложение
  if (Length(s) > 0) and (s[Length(s)] in ['.', '!', '?']) then
    Inc(Result);
end;


function TSiteStats.CountNonSpaceChars(s: string): Integer;
var
  i: Integer;
begin
  Result := 0;

  // Удаляем пробелы в начале и конце строки
  s := Trim(s);

  // Проверяем каждый символ строки
  for i := 1 to Length(s) do
  begin
    // Увеличиваем счетчик, если символ не является пробелом или разделителем
    if not (s[i] in [' ', '.', '!', '?', ',', ';', ':', '-', #9]) then
      Inc(Result);
  end;
end;

function TSiteStats.TimeToReadingInMinutes(words_total : Integer): Integer;
const
  Words_Per_Minutes : Integer = 150;
begin
  Result := words_total div Words_Per_Minutes;
end;

function TSiteStats.ReplaceStats(s: string): String;
var
  CharactersCount : Integer;
  WordsCount : Integer;
  SentencesCount : Integer;
  TTR : Integer;
  temp : String;
begin
     temp := s;

     s := StripHTML(s);
     CharactersCount:= CountNonSpaceChars(s);
     WordsCount:=CountWords(s);
     SentencesCount:=CountSentences(s);
     TTR:=TimeToReadingInMinutes(WordsCount);
     temp := StringReplace(temp, 'TTR()', IntToStr( TTR ), [rfReplaceAll, rfIgnoreCase]);
     temp := StringReplace(temp, 'CHARS()', IntToStr( CharactersCount ), [rfReplaceAll, rfIgnoreCase]);
     temp := StringReplace(temp, 'WORDS()', IntToStr( WordsCount ), [rfReplaceAll, rfIgnoreCase]);
     Result := StringReplace(temp, 'SENTS()',  IntToStr( SentencesCount ), [rfReplaceAll, rfIgnoreCase]);
end;

end.