szovegertesimutato_score/
lib.rs

1use regex::Regex;
2
3pub struct TextComprehensionIndex;
4
5impl TextComprehensionIndex {
6    pub fn new() -> Self {
7        TextComprehensionIndex
8    }
9
10    pub fn calculate(&self, text: &str) -> f64 {
11        let sentence_count = self.count_sentences(text);
12        let word_count = self.count_words(text);
13        let syllable_count = self.count_syllables(text);
14
15        if word_count == 0 || sentence_count == 0 {
16            return 0.0;
17        }
18
19        let words_per_sentence = word_count as f64 / sentence_count as f64;
20        let syllables_per_word = syllable_count as f64 / word_count as f64;
21
22        // Text Comprehension Index formula
23        let index = 206.835 - (1.015 * words_per_sentence) - (84.6 * syllables_per_word);
24
25        index.clamp(0.0, 100.0)
26    }
27
28    fn count_sentences(&self, text: &str) -> usize {
29        let re = Regex::new(r"[.!?]").unwrap();
30        re.find_iter(text).count()
31    }
32
33    fn count_words(&self, text: &str) -> usize {
34        let re = Regex::new(r"\b\w+\b").unwrap();
35        re.find_iter(text).count()
36    }
37
38    fn count_syllables(&self, text: &str) -> usize {
39        let re = Regex::new(r"[aeiouáéíóöőúüűAEIOUÁÉÍÓÖŐÚÜŰ]+").unwrap();
40        re.find_iter(text).count()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_hungarian() {
50        let tci = TextComprehensionIndex::new();
51        let text = "Ez egy tesztszöveg. Azért készült, hogy ellenőrizze a szövegértési mutatót.";
52        let score = tci.calculate(text);
53        assert!(score >= 0.0 && score <= 100.0);
54    }
55
56    #[test]
57    fn test_edge_cases() {
58        let tci = TextComprehensionIndex::new();
59        let text = "";
60        let score = tci.calculate(text);
61        assert_eq!(score, 0.0);
62
63        let text = "A.";
64        let score = tci.calculate(text);
65        assert!(score >= 0.0 && score <= 100.0);
66    }
67}