-
Notifications
You must be signed in to change notification settings - Fork 427
/
TextUtilities.java
executable file
·1610 lines (1467 loc) · 55.8 KB
/
TextUtilities.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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.grobid.core.utilities;
import org.grobid.core.analyzers.GrobidAnalyzer;
import org.grobid.core.exceptions.GrobidException;
import org.grobid.core.layout.LayoutToken;
import org.grobid.core.lexicon.Lexicon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
/**
* Class for holding static methods for text processing.
*
*/
public class TextUtilities {
public static final String punctuations = " •*,:;?.!)-−–\"“”‘’'`$]*\u2666\u2665\u2663\u2660\u00A0。、,・";
public static final String fullPunctuations = "(([ •*,:;?.!/))-−–‐«»„\"“”‘’'`$#@]*\u2666\u2665\u2663\u2660\u00A0。、,・";
public static final String restrictedPunctuations = ",:;?.!/-–«»„\"“”‘’'`*\u2666\u2665\u2663\u2660。、,・";
public static String delimiters = "\n\r\t\f\u00A0\u200C" + fullPunctuations;
public static final String OR = "|";
public static final String NEW_LINE = "\n";
public static final String SPACE = " ";
public static final String COMMA = ",";
public static final String QUOTE = "'";
public static final String END_BRACKET = ")";
public static final String START_BRACKET = "(";
public static final String SHARP = "#";
public static final String COLON = ":";
public static final String DOUBLE_QUOTE = "\"";
public static final String ESC_DOUBLE_QUOTE = """;
public static final String LESS_THAN = "<";
public static final String ESC_LESS_THAN = "<";
public static final String GREATER_THAN = ">";
public static final String ESC_GREATER_THAN = ">";
public static final String AND = "&";
public static final String ESC_AND = "&";
public static final String SLASH = "/";
// note: be careful of catastrophic backtracking here as a consequence of PDF noise!
private static final String ORCIDRegex =
"^\\s*(?:(?:https?://)?orcid.org/)?([0-9]{4})\\-?([0-9]{4})\\-?([0-9]{4})\\-?([0-9]{3}[\\dX])\\s*$";
static public final Pattern ORCIDPattern = Pattern.compile(ORCIDRegex);
// the magical DOI regular expression...
static public final Pattern DOIPattern = Pattern
.compile("(10\\.\\d{4,5}\\/[\\S]+[^;,.\\s])");
// a regular expression for arXiv identifiers
// see https://arxiv.org/help/arxiv_identifier and https://arxiv.org/help/arxiv_identifier_for_services
static public final Pattern arXivPattern = Pattern
.compile("(arXiv\\s?(\\.org)?\\s?\\:\\s?\\d{4}\\s?\\.\\s?\\d{4,5}(v\\d+)?)|(arXiv\\s?(\\.org)?\\s?\\:\\s?[ a-zA-Z\\-\\.]*\\s?/\\s?\\d{7}(v\\d+)?)");
// regular expression for PubMed identifiers, last group gives the PMID digits
static public final Pattern pmidPattern = Pattern.compile("((PMID)|(Pub(\\s)?Med(\\s)?(ID)?))(\\s)?(\\:)?(\\s)*(\\d{1,8})");
// regular expression for PubMed Central identifiers (note: contrary to PMID, we include the prefix PMC here, see
// https://www.ncbi.nlm.nih.gov/pmc/pmctopmid/ for instance), last group gives the PMC ID digits
static public final Pattern pmcidPattern = Pattern
.compile("((PMC\\s?(ID)?)|(Pub(\\s)?Med(\\s)?(Central)?(\\s)?(ID)?))(\\s)?(\\:)?(\\s)*(\\d{1,9})");
// a regular expression for identifying url pattern in text
// TODO: maybe find a better regex (better == more robust, not more "standard")
static public final Pattern urlPattern0 = Pattern
.compile("(?i)(https?|ftp)\\s?:\\s?//\\s?[-A-Z0-9+&@#/%?=~_()|!:,.;]*[-A-Z0-9+&@#/%=~_()|]");
static public final Pattern urlPattern = Pattern
.compile("(?i)(https?|ftp)\\s{0,2}:\\s{0,2}\\/\\/\\s{0,2}[-A-Z0-9+&@#\\/%?=~_()|!:.;]*[-A-Z0-9+&@#\\/%=~_()]");
// a regular expression for identifying email pattern in text
// TODO: maybe find a better regex (better == more robust, not more "standard")
static public final Pattern emailPattern = Pattern.compile("\\w+((\\.|-|_|,)\\w+)?\\s?((\\.|-|_|,)\\w+)?\\s?@\\s?\\w+(\\s?(\\.|-)\\s?\\w+)+");
// variant: \w+(\s?(\.|-|_|,)\w+)?(\s?(\.|-|_|,)\w+)?\s?@\s?\w+(\s?(\.|\-)\s?\w+)+
/**
* Replace numbers in the string by a dummy character for string distance evaluations
*
* @param string the string to be processed.
* @return Returns the string with numbers replaced by 'X'.
*/
public static String shadowNumbers(String string) {
int i = 0;
if (string == null)
return string;
String res = "";
while (i < string.length()) {
char c = string.charAt(i);
if (Character.isDigit(c))
res += 'X';
else
res += c;
i++;
}
return res;
}
private static int getLastPunctuationCharacter(String section) {
int res = -1;
for (int i = section.length() - 1; i >= 0; i--) {
if (fullPunctuations.contains("" + section.charAt(i))) {
res = i;
}
}
return res;
}
/** @use LayoutTokensUtil.dehyphenize(List<LayoutToken> tokens) **/
@Deprecated
public static List<LayoutToken> dehyphenize(List<LayoutToken> tokens) {
return LayoutTokensUtil.dehyphenize(tokens);
}
/** @use LayoutTokenUtils.doesRequireDehypenisation(List<LayoutToken> tokens, int i)**/
@Deprecated
protected static boolean doesRequireDehypenisation(List<LayoutToken> tokens, int i) {
return LayoutTokensUtil.doesRequireDehypenisation(tokens, i);
}
public static String dehyphenize(String text) {
GrobidAnalyzer analyser = GrobidAnalyzer.getInstance();
final List<LayoutToken> layoutTokens = analyser.tokenizeWithLayoutToken(text);
return LayoutTokensUtil.toText(LayoutTokensUtil.dehyphenize(layoutTokens));
}
public static String getLastToken(String section) {
String lastToken = section;
int lastSpaceIndex = section.lastIndexOf(' ');
//The last parenthesis cover the case 'this is a (special-one) case'
// where the lastToken before the hypen should be 'special' and not '(special'
/* int lastParenthesisIndex = section.lastIndexOf('(');
if (lastParenthesisIndex > lastSpaceIndex)
lastSpaceIndex = lastParenthesisIndex;*/
if (lastSpaceIndex != -1) {
lastToken = section.substring(lastSpaceIndex + 1, section.length());
} else {
lastToken = section.substring(0, section.length());
}
return lastToken;
}
public static String getFirstToken(String section) {
int firstSpaceIndex = section.indexOf(' ');
if (firstSpaceIndex == 0) {
return getFirstToken(section.substring(1, section.length()));
} else if (firstSpaceIndex != -1) {
return section.substring(0, firstSpaceIndex);
} else {
return section.substring(0, section.length());
}
}
/**
* Text extracted from a PDF is usually hyphenized, which is not desirable.
* This version supposes that the end of line are lost and than hyphenation
* could appear everywhere. So a dictionary is used to control the recognition
* of hyphen.
*
* @param text the string to be processed without preserved end of lines.
* @return Returns the dehyphenized string.
* <p>
* Deprecated method, not needed anymore since the @newline are preserved thanks to the LayoutTokens
* @Use LayoutTokensUtil.dehypenize()
*/
@Deprecated
public static String dehyphenizeHard(String text) {
if (text == null)
return null;
String res = "";
text.replaceAll("\n", SPACE);
StringTokenizer st = new StringTokenizer(text, "-");
boolean hyphen = false;
boolean failure = false;
String lastToken = null;
while (st.hasMoreTokens()) {
String section = st.nextToken().trim();
if (hyphen) {
// we get the first token
StringTokenizer st2 = new StringTokenizer(section, " ,.);!");
if (st2.countTokens() > 0) {
String firstToken = st2.nextToken();
// we check if the composed token is in the lexicon
String hyphenToken = lastToken + firstToken;
//System.out.println(hyphenToken);
/*if (lex == null)
featureFactory.loadLexicon();*/
Lexicon lex = Lexicon.getInstance();
if (lex.inDictionary(hyphenToken.toLowerCase()) &
!(test_digit(hyphenToken))) {
// if yes, it is hyphenization
res += firstToken;
section = section.substring(firstToken.length(), section.length());
} else {
// if not
res += "-";
failure = true;
}
} else {
res += "-";
}
hyphen = false;
}
// we get the last token
hyphen = true;
lastToken = getLastToken(section);
if (failure) {
res += section;
failure = false;
} else
res += SPACE + section;
}
res = res.replace(" . ", ". ");
res = res.replace(" ", SPACE);
return res.trim();
}
/**
* Levenstein distance between two strings
*
* @param s the first string to be compared.
* @param t the second string to be compared.
* @return Returns the Levenshtein distance.
*/
public static int getLevenshteinDistance(String s, String t) {
//if (s == null || t == null) {
// throw new IllegalArgumentException("Strings must not be null");
//}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n + 1]; //'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
/**
* Appending nb times the char c to the a StringBuffer...
*/
public final static void appendN(StringBuffer buffer, char c, int nb) {
for (int i = 0; i < nb; i++) {
buffer.append(c);
}
}
/**
* To replace accented characters in a unicode string by unaccented equivalents:
* é -> e, ü -> ue, ß -> ss, etc. following the standard transcription conventions
*
* @param input the string to be processed.
* @return Returns the string without accent.
*/
public final static String removeAccents(String input) {
if (input == null)
return null;
final StringBuffer output = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
switch (input.charAt(i)) {
case '\u00C0': // À
case '\u00C1': // Ã
case '\u00C2': // Â
case '\u00C3': // Ã
case '\u00C5': // Ã…
output.append("A");
break;
case '\u00C4': // Ä
case '\u00C6': // Æ
output.append("AE");
break;
case '\u00C7': // Ç
output.append("C");
break;
case '\u00C8': // È
case '\u00C9': // É
case '\u00CA': // Ê
case '\u00CB': // Ë
output.append("E");
break;
case '\u00CC': // Ì
case '\u00CD': // Ã
case '\u00CE': // ÃŽ
case '\u00CF': // Ã
output.append("I");
break;
case '\u00D0': // Ã
output.append("D");
break;
case '\u00D1': // Ñ
output.append("N");
break;
case '\u00D2': // Ã’
case '\u00D3': // Ó
case '\u00D4': // Ô
case '\u00D5': // Õ
case '\u00D8': // Ø
output.append("O");
break;
case '\u00D6': // Ö
case '\u0152': // Å’
output.append("OE");
break;
case '\u00DE': // Þ
output.append("TH");
break;
case '\u00D9': // Ù
case '\u00DA': // Ú
case '\u00DB': // Û
output.append("U");
break;
case '\u00DC': // Ü
output.append("UE");
break;
case '\u00DD': // Ã
case '\u0178': // Ÿ
output.append("Y");
break;
case '\u00E0': // Ã
case '\u00E1': // á
case '\u00E2': // â
case '\u00E3': // ã
case '\u00E5': // å
output.append("a");
break;
case '\u00E4': // ä
case '\u00E6': // æ
output.append("ae");
break;
case '\u00E7': // ç
output.append("c");
break;
case '\u00E8': // è
case '\u00E9': // é
case '\u00EA': // ê
case '\u00EB': // ë
output.append("e");
break;
case '\u00EC': // ì
case '\u00ED': // Ã
case '\u00EE': // î
case '\u00EF': // ï
output.append("i");
break;
case '\u00F0': // ð
output.append("d");
break;
case '\u00F1': // ñ
output.append("n");
break;
case '\u00F2': // ò
case '\u00F3': // ó
case '\u00F4': // ô
case '\u00F5': // õ
case '\u00F8': // ø
output.append("o");
break;
case '\u00F6': // ö
case '\u0153': // Å“
output.append("oe");
break;
case '\u00DF': // ß
output.append("ss");
break;
case '\u00FE': // þ
output.append("th");
break;
case '\u00F9': // ù
case '\u00FA': // ú
case '\u00FB': // û
output.append("u");
break;
case '\u00FC': // ü
output.append("ue");
break;
case '\u00FD': // ý
case '\u00FF': // ÿ
output.append("y");
break;
default:
output.append(input.charAt(i));
break;
}
}
return output.toString();
}
// ad hoc stopword list for the cleanField method
public final static List<String> stopwords =
Arrays.asList("the", "of", "and", "du", "de le", "de la", "des", "der", "an", "und", "for");
/**
* Remove useless punctuation at the end and beginning of a metadata field.
* <p/>
* Still experimental ! Use with care !
*/
public final static String cleanField(String input0, boolean applyStopwordsFilter) {
if (input0 == null) {
return null;
}
if (input0.length() == 0) {
return null;
}
String input = input0.replace(",,", ",");
input = input.replace(", ,", ",");
int n = input.length();
// characters at the end
for (int i = input.length() - 1; i > 0; i--) {
char c = input.charAt(i);
if ((c == ',') ||
(c == ' ') ||
(c == '.') ||
(c == '-') ||
(c == '_') ||
(c == '/') ||
//(c == ')') ||
//(c == '(') ||
(c == ':')) {
n = i;
} else if (c == ';') {
// we have to check if we have an html entity finishing
if (i - 3 >= 0) {
char c0 = input.charAt(i - 3);
if (c0 == '&') {
break;
}
}
if (i - 4 >= 0) {
char c0 = input.charAt(i - 4);
if (c0 == '&') {
break;
}
}
if (i - 5 >= 0) {
char c0 = input.charAt(i - 5);
if (c0 == '&') {
break;
}
}
if (i - 6 >= 0) {
char c0 = input.charAt(i - 6);
if (c0 == '&') {
break;
}
}
n = i;
} else break;
}
input = input.substring(0, n);
// characters at the begining
n = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if ((c == ',') ||
(c == ' ') ||
(c == '.') ||
(c == ';') ||
(c == '-') ||
(c == '_') ||
//(c == ')') ||
//(c == '(') ||
(c == ':')) {
n = i;
} else break;
}
input = input.substring(n, input.length()).trim();
if ((input.endsWith(")")) && (input.startsWith("("))) {
input = input.substring(1, input.length() - 1).trim();
}
if ((input.length() > 12) &&
(input.endsWith(""")) &&
(input.startsWith("""))) {
input = input.substring(6, input.length() - 6).trim();
}
if (applyStopwordsFilter) {
boolean stop = false;
while (!stop) {
stop = true;
for (String word : stopwords) {
if (input.endsWith(SPACE + word)) {
input = input.substring(0, input.length() - word.length()).trim();
stop = false;
break;
}
}
}
}
return input.trim();
}
/**
* Segment piece of text following a list of segmentation characters.
* "hello, world." -> [ "hello", ",", "world", "." ]
*
* @param input the string to be processed.
* @param input the characters creating a segment (typically space and punctuations).
* @return Returns the string without accent.
*/
public final static List<String> segment(String input, String segments) {
if (input == null)
return null;
ArrayList<String> result = new ArrayList<String>();
String token = null;
String seg = " \n\t";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
int ind = seg.indexOf(c);
if (ind != -1) {
if (token != null) {
result.add(token);
token = null;
}
} else {
int ind2 = segments.indexOf(c);
if (ind2 == -1) {
if (token == null)
token = "" + c;
else
token += c;
} else {
if (token != null) {
result.add(token);
token = null;
}
result.add("" + segments.charAt(ind2));
}
}
}
if (token != null)
result.add(token);
return result;
}
/**
* Encode a string to be displayed in HTML
* <p/>
* If fullHTML encode, then all unicode characters above 7 bits are converted into
* HTML entitites
*/
public static String HTMLEncode(String string) {
return HTMLEncode(string, false);
}
public static String HTMLEncode(String string, boolean fullHTML) {
if (string == null)
return null;
if (string.length() == 0)
return string;
//string = string.replace("@BULLET", "•");
StringBuffer sb = new StringBuffer(string.length());
// true if last char was blank
boolean lastWasBlankChar = false;
int len = string.length();
char c;
for (int i = 0; i < len; i++) {
c = string.charAt(i);
if (c == ' ') {
// blank gets extra work,
// this solves the problem you get if you replace all
// blanks with , if you do that you loss
// word breaking
if (lastWasBlankChar) {
lastWasBlankChar = false;
//sb.append(" ");
} else {
lastWasBlankChar = true;
sb.append(' ');
}
} else {
lastWasBlankChar = false;
//
// HTML Special Chars
if (c == '"')
sb.append(""");
else if (c == '\'')
sb.append("'");
else if (c == '&') {
boolean skip = false;
// we don't want to recode an existing hmlt entity
if (string.length() > i + 3) {
char c2 = string.charAt(i + 1);
char c3 = string.charAt(i + 2);
char c4 = string.charAt(i + 3);
if (c2 == 'a') {
if (c3 == 'm') {
if (c4 == 'p') {
if (string.length() > i + 4) {
char c5 = string.charAt(i + 4);
if (c5 == ';') {
skip = true;
}
}
}
}
} else if (c2 == 'q') {
if (c3 == 'u') {
if (c4 == 'o') {
if (string.length() > i + 5) {
char c5 = string.charAt(i + 4);
char c6 = string.charAt(i + 5);
if (c5 == 't') {
if (c6 == ';') {
skip = true;
}
}
}
}
}
} else if (c2 == 'l' || c2 == 'g') {
if (c3 == 't') {
if (c4 == ';') {
skip = true;
}
}
}
}
if (!skip) {
sb.append("&");
} else {
sb.append("&");
}
} else if (c == '<')
sb.append("<");
else if (c == '>')
sb.append(">");
/*else if (c == '\n') {
// warning: this can be too much html!
sb.append("<br/>");
}*/
else {
int ci = 0xffff & c;
if (ci < 160) {
// nothing special only 7 Bit
sb.append(c);
} else {
if (fullHTML) {
// Not 7 Bit use the unicode system
sb.append("&#");
sb.append(Integer.valueOf(ci).toString());
sb.append(';');
} else
sb.append(c);
}
}
}
}
return sb.toString();
}
public static String normalizeRegex(String string) {
string = string.replace("&", "\\\\&");
string = string.replace("&", "\\\\&");
string = string.replace("+", "\\\\+");
return string;
}
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
static public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// e.printStackTrace();
throw new GrobidException("An exception occured while running Grobid.", e);
} finally {
try {
is.close();
} catch (IOException e) {
// e.printStackTrace();
throw new GrobidException("An exception occured while running Grobid.", e);
}
}
return sb.toString();
}
/**
* Count the number of digit in a given string.
*
* @param text the string to be processed.
* @return Returns the number of digit chracaters in the string...
*/
static public int countDigit(String text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isDigit(c))
count++;
}
return count;
}
/**
* Map special ligature and characters coming from the pdf
*/
static public String clean(String token) {
if (token == null)
return null;
if (token.length() == 0)
return token;
String res = "";
int i = 0;
while (i < token.length()) {
switch (token.charAt(i)) {
// ligature
case '\uFB00': {
res += "ff";
break;
}
case '\uFB01': {
res += "fi";
break;
}
case '\uFB02': {
res += "fl";
break;
}
case '\uFB03': {
res += "ffi";
break;
}
case '\uFB04': {
res += "ffl";
break;
}
case '\uFB06': {
res += "st";
break;
}
case '\uFB05': {
res += "ft";
break;
}
case '\u00E6': {
res += "ae";
break;
}
case '\u00C6': {
res += "AE";
break;
}
case '\u0153': {
res += "oe";
break;
}
case '\u0152': {
res += "OE";
break;
}
// quote
case '\u201C': {
res += "\"";
break;
}
case '\u201D': {
res += "\"";
break;
}
case '\u201E': {
res += "\"";
break;
}
case '\u201F': {
res += "\"";
break;
}
case '\u2019': {
res += "'";
break;
}
case '\u2018': {
res += "'";
break;
}
// bullet uniformity
case '\u2022': {
res += "•";
break;
}
case '\u2023': {
res += "•";
break;
}
case '\u2043': {
res += "•";
break;
}
case '\u204C': {
res += "•";
break;
}
case '\u204D': {
res += "•";
break;
}
case '\u2219': {
res += "•";
break;
}
case '\u25C9': {
res += "•";
break;
}
case '\u25D8': {
res += "•";
break;
}
case '\u25E6': {
res += "•";
break;
}
case '\u2619': {
res += "•";
break;
}
case '\u2765': {
res += "•";
break;
}
case '\u2767': {
res += "•";
break;
}
case '\u29BE': {
res += "•";
break;
}
case '\u29BF': {
res += "•";
break;
}
// asterix
case '\u2217': {
res += " * ";
break;
}
// typical author/affiliation markers
case '\u2020': {
res += SPACE + '\u2020';
break;
}
case '\u2021': {
res += SPACE + '\u2021';
break;
}
case '\u00A7': {
res += SPACE + '\u00A7';
break;
}
case '\u00B6': {
res += SPACE + '\u00B6';
break;
}
case '\u204B': {
res += SPACE + '\u204B';
break;
}
case '\u01C2': {
res += SPACE + '\u01C2';
break;
}
// default
default: {
res += token.charAt(i);
break;
}
}
i++;
}
return res;
}
public static String formatTwoDecimals(double d) {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat) nf;
df.applyPattern("#.##");
return df.format(d);
}
public static String formatFourDecimals(double d) {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat) nf;
df.applyPattern("#.####");
return df.format(d);
}
public static boolean isAllUpperCase(String text) {
for (int i = 0; i < text.length(); i++) {
if (!Character.isUpperCase(text.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isAllLowerCase(String text) {
for (int i = 0; i < text.length(); i++) {
if (!Character.isLowerCase(text.charAt(i))) {
return false;
}
}
return true;
}
public static List<String> generateEmailVariants(String firstName, String lastName) {
// current heuristics:
// "First Last"
// "First L"
// "F Last"
// "First"
// "Last"
// "Last First"
// "Last F"
List<String> variants = new ArrayList<String>();
if (lastName != null) {
variants.add(lastName);
if (firstName != null) {