-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcppSBD.cpp
More file actions
416 lines (329 loc) · 12.3 KB
/
cppSBD.cpp
File metadata and controls
416 lines (329 loc) · 12.3 KB
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
* Copyright (C) 2018
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* File: main.cpp
* Author: 792x
*
* Created on April 22, 2018, 9:36 PM
*/
#include <cstdlib>
#include <string>
#include <algorithm>
#include <regex>
#include <vector>
#include <fstream>
#include <streambuf>
#include <iostream>
using namespace std;
//class declaration
class SentenceSplitter;
class StringBuilder;
//regex constants
regex REGEX_RETURN = regex("[\\n\\r]+");
regex REGEX_FORGOTTEN_SPACE = regex("(.)([\\.!?])([\\D&&\\S&&[^\\.\"'`\\)\\}\\]]])");
regex REGEX_SENTENCE = regex("(['\"`]*[\\(\\{\\[]?[a-zA-Z0-9]+.*?)([\\.!?:])(?:(?=([\\(\\[\\{\"'`\\)\\}\\]<]*[ \031]+)[\\(\\[\\{\"'`\\)\\}\\] ]*([A-Z0-9][a-z]*))|(?=([\\(\\)\"'`\\)\\}<\\] \031]+)\\s))");
regex REGEX_WHITESPACE = regex("\\s+");
regex REGEX_LAST_WORD = regex("\\b([\\w0-9\\.']+)$");
//global variables
vector<string> EnglishAbbreviations(0);
vector<string> EnglishDictionary(0);
string textfile;
//helper class to handle stringbuilding
class StringBuilder {
private:
string main;
string scratch;
const string::size_type ScratchSize = 1024;
// or some other arbitrary number
public:
StringBuilder & append(const string & str) {
scratch.append(str);
if (scratch.size() > ScratchSize) {
main.append(scratch);
scratch.resize(0);
}
return *this;
}
const string & str() {
if (scratch.size() > 0) {
main.append(scratch);
scratch.resize(0);
}
return main;
}
};
//main class used to split sentences
class SentenceSplitter {
public:
/*
* Reads both included dictionary files
*
* @params abbreviations is the list of english abbreviations
* @params dictionary is the list of english words
* @modifies vector EnglishAbbreviations and vector EnglishDictionary
* @returns Two vectors, one containing each english abbreviation
* and another containing each english word
*
*/
int loadDictionaries(string abbreviations = "abbreviations_en.txt",
string dictionary = "dictionary_en.txt") {
string word;
string word2;
ifstream reader(abbreviations);
ifstream reader2(dictionary);
if (!reader) {
cout << "Error opening file" << endl;
return -1;
} else {
while (reader >> word) {
EnglishAbbreviations.push_back(word);
}
reader.close();
}
if (!reader2) {
cout << "Error opening file2" << endl;
return -1;
} else {
while (reader2 >> word2) {
EnglishDictionary.push_back(word2);
}
reader2.close();
}
return 0;
}
/*
* Transforms string to lower case
*
* @pre (input != null)
* @params string input
* @modifies string input
* @returns input such that it is in lower case
* @post \forall(char in input ; char is in lower case)
*
*/
string toLowerCase(string input) {
for (char & ch : input)
ch = tolower(ch);
return input;
}
/*
* Trims leading and trailing spaces of string
*
* @pre (input != null)
* @params string input
* @modifies string input
* @returns string input such that leading and trailing spaces are excluded
*
*/
string toTrimmed(string input) {
return regex_replace(input, regex("^ +| +$|( ) +"), "$1");
}
/*
* removes certain character from a string
*
* @pre (input != null) && (c != null)
* @params string input
* @params char c
* @modifies string input
* @returns string input such that all occurences of char c are removed
* from it
*
*/
string removeChar(string input, char c) {
string result;
for (size_t i = 0; i < input.size(); i++) {
char currentChar = input[i];
if (currentChar != c)
result += currentChar;
}
return result;
}
/*
* Reads all of a textfile into a string
*
* @pre
* @params string filename (default = "text.txt")
* @modifies textfile
*
*/
string loadFile(string filename) {
ifstream t(filename);
string str((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
return str;
}
/*
* Takes a string of text and uses sentence boundary detection to split
* the text into sentences and load each sentence in a vector.
*
* @pre (textfile != null)
* @params string text (default = textfile)
* @modifies vector results
* @returns vector results
* @post \forall(strings in results ; string is a sentence)
*
*/
vector<string> split(string filename = "text.txt") {
vector<string> sentences;
int length = 0;
string text = "";
//load dictionaries
loadDictionaries();
//load file
text = loadFile(filename);
//preprocess text
text = regex_replace(text, REGEX_RETURN, " ");
text = removeChar(text, '\031');
text = regex_replace(text, REGEX_FORGOTTEN_SPACE, "$1$2\031$3");
text = text + "\n";
StringBuilder* currentSentence = new StringBuilder();
int end = 0;
//iterate over all matches with REGEX_SENTENCE
for (sregex_iterator i = sregex_iterator(text.begin(), text.end(),
REGEX_SENTENCE); i != sregex_iterator(); ++i) {
smatch matches = *i;
end = matches.suffix().second - text.begin();
string sentence = toTrimmed(matches[1].str());
string punctuation = matches[2].str();
string stuffAfterPeriod = matches.str(3);
if (stuffAfterPeriod.empty()) {
stuffAfterPeriod = matches.str(5);
if (stuffAfterPeriod.empty()) {
stuffAfterPeriod = "";
} else {
end = matches[5].second - text.begin();
}
} else {
end = matches[5].second - text.begin();
}
sregex_token_iterator iter(sentence.begin(), sentence.end(),
REGEX_WHITESPACE, -1);
sregex_token_iterator endz;
vector<string> words;
for (; iter != endz; ++iter) {
words.push_back(*iter);
}
length += words.size();
string nextWord = matches[4].str();
if (nextWord.empty()) {
nextWord = "";
}
if (punctuation.compare(".") == 0) {
// We check if word before period is abbreviation, this is the case if:
// 1) all consonants and not all capitalised and contain no lower case
// 2) a span of single letters followed by periods
// 3) a single letter (except I).
// 4) in the known abbreviations list.
// If any case is true, then the period is NOT a full stop.
smatch morematches;
string lastWord = "";
if (regex_search(sentence, morematches, REGEX_LAST_WORD)) {
lastWord = morematches.str(); // works till here
}
if ((!regex_match(sentence, morematches, regex(".*[AEIOUaeiou]+.*"))
&& regex_match(sentence, morematches, regex(".*[a-z]+.*"))
&& !regex_match(sentence, morematches, regex(".*[y]+.*")))
|| regex_match(sentence, morematches, regex("([a-zA-Z][\\.])+"))
|| (regex_match(sentence, morematches, regex("^[A-Za-z]$"))
&& !regex_match(sentence, morematches, regex("^[I]$")))
|| find(EnglishAbbreviations.begin(), EnglishAbbreviations.end(),
toLowerCase(lastWord)) != EnglishAbbreviations.end()) {
// then we have an abbreviation
if ((find(EnglishDictionary.begin(), EnglishDictionary.end(),
nextWord) != EnglishDictionary.end()) && length > 6) {
currentSentence->append(sentence);
currentSentence->append(punctuation);
currentSentence->append(toTrimmed(stuffAfterPeriod));
sentences.push_back(currentSentence->str());
currentSentence = new StringBuilder();
length = 0;
} else {
// no sentence break
currentSentence->append(sentence);
currentSentence->append(punctuation);
string::size_type loc = stuffAfterPeriod.find('\031', 0);
if (loc != string::npos) {
currentSentence->append(" ");
}
}
} else {
// no sentence break
currentSentence->append(sentence);
currentSentence->append(punctuation);
currentSentence->append(toTrimmed(stuffAfterPeriod));
sentences.push_back(currentSentence->str());
currentSentence = new StringBuilder();
length = 0;
}
} else {
// only consider sentences if ":" comes after at least 6
// words from start of sentence
smatch extramatches;
if (regex_match(punctuation, extramatches, regex("[!?]"))
|| (punctuation.compare(":") == 0 && length > 6)) {
// sentence break
currentSentence->append(sentence);
currentSentence->append(punctuation);
currentSentence->append(toTrimmed(stuffAfterPeriod));
sentences.push_back(currentSentence->str());
currentSentence = new StringBuilder();
length = 0;
} else {
// no sentence break
currentSentence->append(sentence);
currentSentence->append(punctuation);
string::size_type loc = stuffAfterPeriod.find('\031', 0);
if (loc != string::npos) {
currentSentence->append(" ");
}
}
}
}
if (end < text.length()) {
//check after last sentence
string lastPart = text.substr(end);
if (!lastPart.empty()) {
currentSentence->append(lastPart);
}
}
// if currentSentence is not empty we add it to sentence vector
if (currentSentence->str().length() > 0) {
sentences.push_back(toTrimmed(currentSentence->str()));
}
vector<string> results(0);
for (int i = 0; i < sentences.size(); i++) {
string str = sentences.at(i);
str = removeChar(str, '\031');
// add to result vector
results.push_back(str);
}
return results;
}
};
int main(int argc, char** argv) {
//new pointer to class
SentenceSplitter *ss;
//use class pointer's split command like this
vector<string> results = ss->split("texthard.txt");
//result vector now usable and contains all sentences
//i.e. print all sentences:
for (auto i = results.begin(); i != results.end(); ++i) {
cout << *i << endl;
}
//delete pointer to class
delete ss;
return 0;
}