script/nsp2regex.pl untested

filter: Statementstmt 0.0% 0 / 106 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 166 CC 1 SCAR 6.9
CC
1
Cov
0%
escape
2.0
minimalUsageNotes
2.0
showHelp
2.0
CRAP 2.0
1 #!/usr/local/bin/perl -w
2  
3 # THIS PROGRAM ORIGINALLY BELONGS TO THE SenseTools PACKAGE
4 # (http://www.d.umn.edu/~tpederse/sensetools.html) DEVELOPED
5 # BY SATANJEEV BANERJEE AND DR. TED PEDERSEN. IT HAS BEEN
6 # INCLUDED IN SenseClusters DISTRIBUTION FOR CONVENIENCE REASONS.
7  
8 # BELOW IS THE DOCUMENTATION THAT IS COMPILED FROM THE READMES'
9 # OF THE SenseTools PACKAGE
10  
11 =head1 NAME
12  
13 nsp2regex.pl - Convert Text-NSP output into regular expressions to be used for feature matching
14  
15 =head1 SYNOPSIS
16  
17 nsp2regex.pl [OPTIONS] SOURCE [[, SOURCE] ...]
18  
19 =head1 DESCRIPTION
20  
21 Takes n-word sequences and represents them as regular
22 expressions. These can then be used to identify lexical
23 features in a given data, and convert a lexical element
24 files from text into feature vectors.
25  
26 =head1 INPUT
27  
28 =head2 Required Arguments:
29  
30 =head3 SOURCE
31  
32 The SOURCE is a file containing the list of features.
33 The features are required to be in specific format:
34  
35 the_feature_token<>
36  
37 Unigram feature: temperature<>
38 Bigram feature: daily<>temperature<>
39
40 count.pl or statistic.pl (both part of the Ngram Statistics Package)
41 created output can be directly used as the SOURCE file.
42  
43 =head2 Optional Arguments
44  
45 =head3 --token FILE
46  
47 Uses tokens contained in FILE to create the separator
48 between tokens, when window size of SOURCE n-gram is
49 greater than the 'n' of the n-gram. Window sizes for
50 n-grams in SOURCE can be defined using the --extended
51 option in count.pl.
52  
53 =head3 --version
54  
55 Prints the version number.
56  
57 =head3 --help
58  
59 Prints this help message.
60  
61 =head1 OUTPUT
62  
63 Outputs the generated regular expressions to stdout.
64  
65 =head1 Explanation of the created Regular Expressions
66  
67 =head2 Default Regular Expression (without Skipping Intermediate Tokens):
68  
69 By default nsp2regex.pl creates regex's that match space
70 separated tokens. The regular expressions that nsp2regex.pl creates
71 are based on the assumption that the text on
72 which these regex's are going to be used has tokens separated by a
73 single space. Further the regular expressions thus created ignore XML
74 tags and non-tokens, as described in the examples above.
75  
76 For example, the following line in the input to nsp2regex.pl:
77  
78 a<>bigram<>
79  
80 is converted to the following regex:
81  
82 /\s(<[^>]*>)*a(<[^>]*>)*\s(<[^>]*>\s)*(<[^>]*>)*bigram(<[^>]*>)*\s/ @name = a<>bigram
83  
84 In this output, everything from the first / to the last / constitutes
85 the regular expression. The portion "@name = a<>bigram" is used by
86 xml2arff.pl (from SenseTools package) for giving a name to the attribute
87 corresponding to this regular expression.
88  
89 =head2 What This Regular Expression will Match:
90  
91 This regular expression defines a feature that will match the tokens
92 "a" and "bigram" under the following conditions:
93  
94 i> Tokens "a" and "bigram" have exactly one space to their left and
95 right. For example, this regex will match the sentence " this is a
96 bigram ". This regex will not match the sentence " i wanna bigram "
97 nor the sentence " i have a bigrams ". It will not even match " I
98 have a bigram ". This is because nsp2regex.pl creates regular
99 expressions that assume that there is exactly ONE space character
100 between tokens!
101  
102 ii> Tokens "a" and "bigram" are bounded by one or more xml tags or
103 non-tokens, that is a sequence of characters that start with '<'
104 and end with '>'. eg: this regex will match the sentence : " this
105 is a <head>bigram</head> ". This regex will also match " this is
106 a <head>bigram<senseid=20/></head> ".
107  
108 iii> tokens "a" and "bigram" are separated by one or more space
109 separated xml tags. eg: this regex will match the sentence " this
110 is a <,> bigram ". It will also match " this is a <,> bigram <!>
111 " and " this is a <,> <head>bigram</head> ".
112  
113 iv> combinations of the above cases.
114  
115 =head2 Explanation of this Regular Expression:
116  
117 Following is an explanation of the various parts of the regular
118 expression:
119  
120 /\s(<[^>]*>)*a(<[^>]*>)*\s(<[^>]*>\s)*(<[^>]*>)*bigram(<[^>]*>)*\s/ @name = a<>bigram
121  
122  
123 a> All the portion between the first '/' and the last '/' is the regular
124 expression.
125  
126 b> The regular expression starts with requiring a single space
127 character, \s. This is consistent with the assumption that every
128 token has exactly one space to its left and one to its right.
129  
130 c> The next chunk is (<[^>]*>)*a(<[^>]*>)*
131 Note that the portion (<[^>]*>) represents exactly our definition
132 of an XML tag, namely that it should start with a '<', have 0 or
133 more characters, except the '>' character, and then end with the
134 '>' character. The '*' outside the bracket denotes that we are
135 willing to match 0 or more such tags. After that, we wish to match
136 a single occurrence of the first token, 'a', again followed by 0 or
137 more tags. Note that the tags are "stuck" to the token 'a', in that
138 there is no space between the tag and the token 'a'. Of course if
139 in the text there is a space between an XML tag and 'a', then the
140 space would match the space in <b> above.
141  
142 d> Having matched token 'a' with 0 or more tags "stuck" to its right
143 and left, we now wish to match exactly a single space character
144 through the \s. Again this corresponds to our assumption that
145 tokens in the text are separated by exactly one space character!
146  
147 e> The next chunk (<[^>]*>\s)* is again our familiar XML tag. This
148 time we wish to "skip" over 0 or more occurrences of any XML tag
149 that lie between the first and the second token, ie between 'a' and
150 'bigram'. Since these are not "stuck" to the next token 'bigram',
151 they are space separated from each other and from 'bigram'. Hence,
152 for every token we match, we also match a space character!
153  
154 f> The next chunk is (<[^>]*>)*bigram(<[^>]*>)* which is exactly like
155 the chunk for 'a' in point <c> above.
156  
157 g> Finally we wish to match a single space character \s.
158  
159 h> The portion after the last '/' @name = a<>bigram creates a "name"
160 for this feature. This name is used by xml2arff (from SenseTools
161 package) while creating the vector output of the input XML file.
162 While this name is not necessary, it makes the vector output more
163 human-readable.
164  
165 =head2 Regular Expression with Skipping of Intermediate Tokens:
166  
167 nsp2regex.pl can create regular expressions that ignore
168 one or more tokens that occur between the tokens to be
169 matched. This can be switched "ON" by having the
170 directive "@count.WindowSize=..." in the input file to
171 nsp2regex.pl. We need to provide nsp2regex.pl with the same token file
172 we provide preprocess.pl... say following is the token file:
173  
174 /<head>\w+<\/head>/
175 /\w+/
176  
177 Let the input file to the nsp2regex.pl program be the following:
178  
179 @count.WindowSize=3
180 a<>bigram<>
181  
182 then, the output regular expression from nsp2regex.pl is:
183  
184
185 /\s(<[^>]*>)*a(<[^>]*>)*\s(<[^>]*>\s)*((<[^>]*>)*((<head>\w+<\/head>)|(\w+))(<[^>]*>)*\s(<[^>]*>\s)*){0,1}(<[^>]*>)*bigram(<[^>]*>)*\s/ @name = a<>bigram<>1
186  
187 =head2 What This Regular Expression will Match:
188  
189 This regular expression will match the tokens "a" and "bigram"
190 separated by 0 or 1 occurrences of the white space separated token
191 ((<head>\w+<\/head>)|(\w+)). This is the token definitions obtained
192 from the token.txt file above!
193  
194 For example, this regular expression will match the following
195 sentences:
196  
197 " this is a funny bigram "
198 " this is a bigram "
199 " this is a <head>nice</head> bigram "
200 " this is a <,> bigram "
201 " this is a <,> <head>nice</head> bigram "
202  
203 This regular expression will not match:
204  
205 " this is a really big bigram ",
206 " i wanna write bigram ".
207 " this is a , bigram ",
208  
209 =head2 Explanation of this Regular Expression:
210  
211 Following is a description of various parts of the regular expression:
212  
213
214 /\s(<[^>]*>)*a(<[^>]*>)*\s(<[^>]*>\s)*((<[^>]*>)*((<head>\w+<\/head>)|(\w+))(<[^>]*>)*\s(<[^>]*>\s)*){0,1}(<[^>]*>)*bigram(<[^>]*>)*\s/ @name = a<>bigram<>1
215  
216 On careful observation one will notice that the above regular
217 expression differs from the previous regular expression (section 6.1.2)
218 in only one portion.
219  
220 Specifically the portion \s(<[^>]*>)*a(<[^>]*>)*\s(<[^>]*>\s)* is the
221 same as above... this matches a space, followed by 'a'
222 with XML tags or non-token characters (within <> brackets) stuck to
223 its left and right, followed by a single space, followed by 0 or more
224 XML tags and non-token characters, with a space after every such tag.
225  
226 Further note that the portion (<[^>]*>)*bigram(<[^>]*>)*\s is again
227 the same as before... they match 'bigram' with XML tags and non-token
228 character tags stuck to its left and right, followed by a single
229 space.
230  
231 Thus the only "new" portion in this regex is
232  
233 ((<[^>]*>)*((<head>\w+<\/head>)|(\w+))(<[^>]*>)*\s(<[^>]*>\s)*){0,1}
234  
235 We call this the "separator" portion of the regex; this is the portion
236 that allows for the "ignoring" of up to one token between the tokens
237 'a' and 'bigram'. This token can be either a <head>\w+</head> or a
238 \w+.
239  
240 a> Observe that the entire section is within a pair of round brackets,
241 followed by a {0,1}. This says that this portion is allowed to
242 occur 0 or 1 times. This is consistent with the window size of
243 3... besides 'a' and 'bigram', we allow at most one other token to
244 come into the window. If our window size were to be 10 say, this
245 would be {0,8}.
246  
247 b> The first part inside this bracketed portion is
248 (<[^>]*>)*((<head>\w+<\/head>)|(\w+))(<[^>]*>)*. This says that we
249 are willing to match either a <head>\w+</head> or a \w+. Further
250 whatever we match can be preceeded or followed by an XML tag or a
251 non-token character ensconced with the angular brackets <>.
252  
253 c> Having matched either of the two options, we wish to match a single
254 space, \s, followed by one or more XML tags or non-tokens, in
255 keeping with our desire to skip these tags!
256  
257 e> And, as mentioned in <a> above, we would like to do this matching
258 at most once, that is there will be at most one such token between
259 'a' and 'bigram'.
260  
261 f> The name of the feature has also changed to @name = a<>bigram<>1
262 implying that we are allowing at most one token to come in between
263 our two main tokens!
264  
265 =head2 A Fine Point about nsp2regex.pl:
266  
267 Fine Point 1: Certain characters, like '.', '*', '?' etc have special
268 meaning when used within a regular expression. If these characters
269 occur in the tokens that the regular expression is being built from,
270 they are "escaped" (by prepending them with a slash '\'). Following is
271 a list of characters that are so escaped: '\', '/', '|', '(', ')',
272 '[', ']', '{', '}', '^', '$', '*', '+', '?' and '.'
273  
274 =head1 AUTHORS
275  
276 Satanjeev Banerjee, Carnegie-Mellon University
277  
278 Ted Pedersen, University of Minnesota, Duluth
279 tpederse at d.umn.edu
280  
281 =head1 COPYRIGHT
282  
283 Copyright (c) 2001-2008, Satanjeev Banerjee and Ted Pedersen
284  
285 This program is free software; you can redistribute it and/or modify it under
286 the terms of the GNU General Public License as published by the Free Software
287 Foundation; either version 2 of the License, or (at your option) any later
288 version.
289  
290 This program is distributed in the hope that it will be useful, but WITHOUT
291 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
292 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
293  
294 You should have received a copy of the GNU General Public License along with
295 this program; if not, write to
296  
297 The Free Software Foundation, Inc.,
298 59 Temple Place - Suite 330,
299 Boston, MA 02111-1307, USA.
300  
301 =cut
302  
303 # nsp2regex.pl version 0.3
304 # Program to create regex's from output of count.pl or statistic.pl
305 #
306 ##############################################################################
307 # ChangeLog
308 #
309 # May 10, 2003 TDP renamed bsp2regex as nsp2regex
310 #
311 ##############################################################################
312  
313 #-----------------------------------------------------------------------------
314 # Start of program
315 #-----------------------------------------------------------------------------
316  
317 # we have to use commandline options, so use the necessary package!
318 use Getopt::Long;
319  
320 # first check if no commandline options have been provided... in which case
321 # print out the usage notes!
322 if ( $#ARGV == -1 )
323 {
324 &minimalUsageNotes();
325 exit;
326 }
327  
328 # now get the options!
329 GetOptions("version", "help", "token=s", "sort" );
330  
331 # if help has been requested, print out help!
332 if ( defined $opt_help )
333 {
334 $opt_help = 1;
335 &showHelp();
336 exit;
337 }
338  
339 # if version has been requested, show version!
340 if ( defined $opt_version )
341 {
342 $opt_version = 1;
343 &showVersion();
344 exit;
345 }
346  
347 # get the separator token!
348 if ( defined $opt_token )
349 {
350 if ( !( -e $opt_token))
351 {
352 print "Cant find token definition file $opt_token.\n";
353 askHelp();
354 exit;
355 }
356
357 open TOKEN, $opt_token || die "Couldnt open $opt_token\n";
358
359 while(<TOKEN>)
360 {
361 chomp;
362 s/^\s*//g;
363 s/\s*$//g;
364 if (length($_) <= 0) { next; }
365 if (!(/^\//) || !(/\/$/))
366 {
367 print STDERR "Ignoring regex with no delimiters: $_\n";
368 next;
369 }
370 s/^\///;
371 s/\/$//;
372 push @tokenRegex, $_;
373 }
374 close TOKEN;
375 }
376 else
377 {
378 push @tokenRegex, "\\w+";
379 push @tokenRegex, "[\.,;:\?!]";
380 }
381  
382 # create the complete token regex
383 $tokenizerRegex = "";
384  
385 foreach $token (@tokenRegex)
386 {
387 if ( length($tokenizerRegex) > 0 )
388 {
389 $tokenizerRegex .= "|";
390 }
391 $tokenizerRegex .= "(";
392 $tokenizerRegex .= $token;
393 $tokenizerRegex .= ")";
394 }
395  
396 # if you dont have any tokens to work with, abort
397 if ( $#tokenRegex < 0 )
398 {
399 print "No token definitions to work with.\n";
400 askHelp();
401 exit;
402 }
403  
404 $tokenizerRegex = "((<[^>]*>)*(" . $tokenizerRegex . ")(<[^>]*>)*\\s(<[^>]*>\\s)*)";
405  
406 # now the meaty part!
407  
408 while ( <> )
409 {
410 chomp;
411
412 if ( /^@/ && !(/^@@/) )
413 {
414
415 if ( $_ =~ /^@[^\.]*.WindowSize/ )
416 {
417 s/^[^=]*=//;
418 $declaredWindowSize = $_;
419 }
420 next;
421 }
422
423 if ( /^@@/ ) { s/^@@/@/; }
424 if (!(/<>/)) { next; }
425  
426 @words = split(/<>/);
427 if ( $_ !~ /<>$/ ) { pop @words; }
428  
429 # if no words, then quit
430 if (!(@words)) { next; }
431  
432 # create the name using the <>
433 $name = join ("<>", @words);
434  
435 if (defined $declaredWindowSize)
436 {
437 $windowSize = $declaredWindowSize - $#words - 1;
438 }
439 else
440 {
441 $windowSize = 0;
442 }
443  
444 # stick the window size in if windowSize > 0
445 if ( $windowSize ) { $name .= "<>" . $windowSize; }
446
447 # escape all the words
448 for ($i = 0; $i <= $#words; $i++)
449 {
450 $words[$i] = escape($words[$i]);
451 }
452  
453 # wrap all the words in tags
454 for ($i = 0; $i <= $#words; $i++)
455 {
456 $words[$i] = "(<[^>]*>)*" . $words[$i] . "(<[^>]*>)*";
457 }
458  
459 # create the separator
460 $separator = "\\s(<[^>]*>\\s)*";
461 if ( $windowSize >= 1 )
462 {
463 $separator .= $tokenizerRegex . "\{0,$windowSize\}";
464 }
465  
466 $regex = join($separator, @words);
467 $regex = "/\\s" . $regex . "\\s/";
468  
469 print "$regex \@name = $name\n";
470 }
471  
472 # function to escape a punctuation mark, if necessary
473 sub escape
474 {
475 my $param = shift;
476 $param =~ s/([\\\/\|\(\)\[\]\{\}\^\$\*\+\?\.])/\\$1/g;
477 return $param;
478 }
479  
480 # function to output a minimal usage note when the user has not provided any
481 # commandline options
482 sub minimalUsageNotes
483 {
484 print "Usage: nsp2regex.pl [OPTIONS] SOURCE [[, SOURCE] ...]\n";
485 askHelp();
486 }
487  
488 # function to output help messages for this program
489 sub showHelp
490 {
491 print "Usage: nsp2regex.pl [OPTIONS] SOURCE [[, SOURCE] ...]\n\n";
492  
493 print "Converts n-grams in SOURCE to regular expressions. SOURCE must be the output of\n";
494 print "count.pl or statistic.pl (both part of the Ngram Statistics Package).\n";
495 print "Regular expressions are output to stdout.\n\n";
496  
497 print "OPTIONS:\n\n";
498  
499 print " --version Prints the version number.\n\n";
500  
501 print " --help Prints this help message.\n\n";
502  
503 print " --token FILE Uses tokens contained in FILE to create the separator\n";
504 print " between tokens, when window size of SOURCE n-gram is\n";
505 print " greater than the 'n' of the n-gram. Window sizes for\n";
506 print " n-grams in SOURCE can be defined using the --extended\n";
507 print " option in count.pl.\n\n";
508 }
509  
510 # function to output the version number
511 sub showVersion
512 {
513 # print "nsp2regex.pl - Version 0.3\n";
514 # print "A component of the SenseTools Version 0.3\n";
515 # print "Copyright (C) 2001-2002, Ted Pedersen & Satanjeev Banerjee\n";
516 # print "Date of Last Update: May 10, 2003\n";
517 print '$Id: nsp2regex.pl,v 1.5 2008/03/30 04:40:58 tpederse Exp $';
518 print "\nConvert Text-NSP output to regular expressions for use in feature matching\n";
519 }
520  
521 # function to output "ask for help" message when the user's goofed up!
522 sub askHelp
523 {
524 print STDERR "Type nsp2regex.pl --help for help.\n";
525 }
526  
527