-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextStatistics.java
87 lines (73 loc) · 2.38 KB
/
TextStatistics.java
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
package readability;
import java.util.stream.Stream;
import static java.lang.Math.max;
import static java.lang.String.join;
public class TextStatistics {
public static final long NOT_CALCULATED = -1;
private final String text;
private long characters = NOT_CALCULATED;
private long words = NOT_CALCULATED;
private long sentences = NOT_CALCULATED;
private long syllables = NOT_CALCULATED;
private long polysyllables = NOT_CALCULATED;
public TextStatistics(final String text) {
this.text = text;
}
public long getCharacters() {
if (characters == NOT_CALCULATED) {
characters = text.replaceAll("\\s", "").length();
}
return characters;
}
public long getWords() {
if (words == NOT_CALCULATED) {
words = getWordsStream().count();
}
return words;
}
public long getSentences() {
if (sentences == NOT_CALCULATED) {
sentences = text.split("[!?.]+").length;
}
return sentences;
}
public long getSyllables() {
if (syllables == NOT_CALCULATED) {
syllables = getWordsStream().mapToInt(TextStatistics::countSyllables).sum();
}
return syllables;
}
public long getPolysyllables() {
if (polysyllables == NOT_CALCULATED) {
polysyllables = getWordsStream().filter(TextStatistics::isPolysyllable).count();
}
return polysyllables;
}
public String getText() {
return text;
}
public static int countSyllables(final String word) {
return max(1, word.toLowerCase()
.replaceAll("e$", "")
.replaceAll("[aeiouy]{2}", "a")
.replaceAll("[^aeiouy]", "")
.length());
}
public static boolean isPolysyllable(final String word) {
return countSyllables(word) > 2;
}
public Stream<String> getWordsStream() {
return Stream.of(text.split("[^\\p{Alpha}]+"));
}
@Override
public String toString() {
return String.format(join("%n",
"The text is: %n%s",
"Words: %d",
"Sentences: %d",
"Characters: %d",
"Syllables: %d",
"Polysyllables: %d%n"),
getText(), getWords(), getSentences(), getCharacters(), getSyllables(), getPolysyllables());
}
}