summaryrefslogtreecommitdiff
path: root/splitter/splitter.pl
blob: 0bf1707cb602cdabc4212bc5a38fcfd1d81bccc3 (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
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
#!/usr/bin/perl 
# 
# Sentence Splitter
#

#  Author: Paul Clough
#  With modifications by Daniel M German and Y. Manabe,
#
#
#    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 2 of the
#    License, or (at your option) any later version.
#
#    This patch 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/>.

use strict;

my $abbrv_file = 'abbrev/abbrev.txt';
my $len = 0;

my %ABBREVIATIONS = ();
my $output_file = $ARGV[0];

# where are we running the splitter from?
my $path = $0;
$path =~ s/[^\/]+$//;
if ($path eq '') {
    $path = './';
}

$abbrv_file = $path . $abbrv_file;

die "Usage $0 <filename>.comments" unless $ARGV[0] =~ /\.comments$/;


die "Input file name should end in '.comments' [$output_file]" unless  $output_file =~ s/\.comments$/.sentences/;

open(OUT, ">$output_file") or die("Unable to create output file [$output_file]");


#print length($opt_o);

# Load in the dictionary and find the common words.
# Here, we assume the words in upper case are simply names and one
# word per line - i.e. in same form as /usr/dict/words
# Same assumptions as for dictionary
&loadAbbreviations;

my $text;
#	open(FILE, $opt_f) or die "Can't open $opt_f for reading\n";

my $line;
while (defined ($line = <>)) {
    $text.= $line;
}

# append a newline just in case
$text.="\n";

# - is used to create lines
# = is used to create lines
$text =~ s@\+?\-{3,1000}\+?@ @gmx;
$text =~ s@={3,1000}@ @gmx;
$text =~ s@:{3,1000}@ @gmx;
$text =~ s@\*{3,1000}@ @gmx;

# some characters are used for prettyprinting but never appear in sentences
$text =~ s@\|+@ @gmx;
$text =~ s@\\+@ @gmx;

# let us deal with /* before we do anything
$text =~ s@^[ \t]*/\*@@gmx;
$text =~ s/\*\/[ \t]*$//gmx;
$text =~ s@([^:])// @$1@gmx;


# Replace /\r\n/ with \n only
$text =~ s/\r\n/\n/g;


# now, try to replace the leading/ending character of each line #/-, at most 3 heading characters
# and each repeated as many times as necessaary
$text =~ s/^[ \t]{0,3}[\*\#\/\;]+//gmx;
$text =~ s/^[ \t]{0,3}[\-]+//gmx;

$text =~ s/[\*\#\/]+[ \t]{0,3}$//gmx;
$text =~ s/[\-]+[ \t]{0,3}$//gmx;

# now, try to replace the ending character of each line if it is * or #
$text =~ s/[\*\#]+//gmx;

# at this point we have lines with nothing but spaces, let us get rid of them
$text =~ s/^[ \t]+$/\n/gm;

# let us try the following trick
# We first get rid of \t and replace it with ' '
# we then use \t as a "single line separator" and \n as multiple line.
# so we can match each with a single character.
$text =~ tr/\t/ /;

$text =~ s/\n(?!\n)/\t/g;
$text =~ s/\n\n+/\n/g;
$text .= "\n";

# this gets us in big trouble... licenses that have numeric abbreviations
$text =~ s/v\.\s+2\.0/v<dot> 2<dot>0/g;

while ($text =~ /^([^\n]*)\n/gsm ) {
    my $curr = $1;
#    print "<<$curr\n<<\n";

    # let us count the number of alphabetic chars to check if we are skipping anything we should not
    my $count = 0;
    for my $i (0..length($curr)-1) {
        my $c = substr($curr,$i,1);
        $count++ if ($c ge 'A' && $c le 'z');
    }

    my @sentences = Split_Text($curr);

    my $count2 = 0;

    foreach my $s (@sentences) {
        for my $i (0..length($s)-1) {
            my $c = substr($s,$i,1);
            $count2++ if ($c ge 'A' && $c le 'z');
        }
        print OUT Clean_Sentence($s) , "\n";
    }
    if ($count != $count2) {
        print STDERR "-------------------------------------\n";
        print STDERR "[$curr]\n";
        foreach my $s (@sentences) {
            print STDERR Clean_Sentence($s) , "\n";
        }
        die "Number of printable chars does not match! [$count][$count2]";
    }
}
close OUT;
#print "$text\n";

exit;




#***************************************************************************************************

#***************************************************************************************************
# procedures
#***************************************************************************************************

sub Clean_Sentence
{
    ($_) = @_;
    # check for trailing bullets of different types

    s/^o //;
    s/^\s*[0-9]{1-2}+\s*[\-\)]//;
    s/^[ \t]+//;
    s/[ \t]+$//;
    # remove a trailing -
    s/^[ \t]*[\-\.\s*] +//;

    # replace quotes
    s/\s+/ /g;

    s/['"`]+/<quotes>/g;


    s/:/<colon>/g;

    s/\.+$/./;

    die if /\n/m;

    return $_;

}


sub Split_Text
{
    my ($text) = @_;
    my $len = 0;
    my $next_word;
    my $last_word;
    my $stuff_after_period;
    my $puctuation;
    my @result;
    my $after;
    my $currentSentence = '';
    # this breaks the sentence into 
    # 1. Any text before a separator
    # 2. The separator [.!?:\n]
    # 3.
    while ($text =~ /^ 
                     ([^\.\!\?\:\n]*) #
                     ([\.\!\?\:\n])
                     (?=(.?))
                   /xsm) { #/(?:(?=([([{\"\'`)}\]<]*[ ]+)[([{\"\'`)}\] ]*([A-Z0-9][a-z]*))|(?=([()\"\'`)}\<\] ]+)\s))/sm ) {
	$text = $';    #';
        my $sentenceMatch = $1;
        my $sentence = $1 . $2; 
	my $punctuation = $2;
        $after = $3;
        
        # if next character is not a space, then we are not in a sentence"
        if ($after ne ' ' && $after ne "\t") {
            $currentSentence .= $sentence;
            next;
        }
        #at this point we know that there is a space after
        if ($punctuation eq ':'  || $punctuation eq '?'  || $punctuation eq '!') {
            # let us consider this right here a beginning of a sentence
            push @result, $currentSentence . $sentence;
            $currentSentence = '';
            next;
        }
        if ($punctuation eq '.') {
            # we have a bunch of alternatives
            # for the time being just consider a new sentence

            # TODO
            # simple heuristic... let us check that the next words are not the beginning of a sentence
            # in our library
            # ENDTODO
            
            # is the last word an abbreviation? For this the period has to follow the word
            # this expression might have to be updated to take care of special characters  in names :(
            if ($sentenceMatch =~ /(.?)([^[:punct:]\s]+)$/) {
                my $before = $1;
                my $lastWord = $2;
                #is it an abbreviation
                
                if (length($lastWord) == 1 ) {
                    # single character abbreviations are special...
                    # we will assume they never split the sentence if they are capitalized. 
                    if (($lastWord ge 'A') and
                        ($lastWord le 'Z'))  {
                        $currentSentence .= $sentence;
                        next;
                    }
                    print "last word an abbrev $sentenceMatch lastword [$lastWord] before [$before]\n";

                    # but some are lowercase!
                    if (($lastWord eq 'e') or
                        ($lastWord eq 'i'))  {
                        $currentSentence .= $sentence;
                        next;
                    }
                    print "2 last word an abbrev $sentenceMatch lastword [$lastWord] before [$before]\n";
                } else {
                    
                    $lastWord = lc $lastWord;
                    
                    # only accept abbreviations if the previous char to the abbrev is space or
                    # is empty (beginning of line). This avoids things like .c
                    if (length($before) > 0 and $before eq ' ' and  $ABBREVIATIONS{$lastWord}) {
                        
                        $currentSentence .= $sentence;
                        next;
                    } else {
                        # just keep going, we handle this case below
                    }
                }
                
            }

            push @result, $currentSentence . $sentence;
            $currentSentence = '';
            next;
        }
        die 'We have not dealt with this case';
    }
    push @result, $currentSentence . $text;
    
    #Print_Non_Sentence($text,"\n",'');
    return @result;

}

sub loadAbbreviations 
{
    
    # Initialise var
    my $abbrv_term = '';	
    
    if (open(ABBRV, $abbrv_file)) {
        
        while (defined ($line = <ABBRV>)) {
            chomp($line);
            $ABBREVIATIONS{$line} = $line;	
        }		
        
        close(ABBRV);
    } else {
        die "cannot open dictionary file $abbrv_file: $!";		
    }
}


#***************************************************************************************************