blib/lib/Lingua/EN/Tagger.pm

filter: Statementstmt 91.8% 304 / 331 Branchbran 71.4% 100 / 140 Conditioncond 78.1% 25 / 32 MC/DCmcdc 61.1% 11 / 18 Subroutinesub 94.5% 35 / 37 Podpod 85.7% 12 / 14 totaltotal 85.1% 487 / 572 CC 94 SCAR 20.4
CC
94
Cov
85%
_classify_unknown_word
20.6
get_noun_phrases
11.0
_split_sentences
10.0
CRAP 7.7
↑ Summary
1 package Lingua::EN::Tagger;
2  
3 10 our $VERSION = '0.31';
4  
5 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 10 ▶use 5.008000;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use FileHandle;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use HTML::TokeParser;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use Lingua::Stem::En;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 10 ▶use Storable;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 10 ▶use Memoize;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 # Class variables
19 10 our %_LEXICON; # this holds the word lexicon
20 10 our %_HMM; # this holds the hidden markov model for English grammar
21 10 our $MNP; # this holds the compiled maximal noun phrase regex
22 10 our ($lexpath, $word_path, $tag_path);
23 10 our ($NUM, $GER, $NNP, $ADJ, $PART, $NN, $PREP, $DET, $PAREN, $QUOT, $SEN, $WORD);
24  
25 10 ▶BEGIN { # REGEX SETUP
Subroutine BEGIN: called CC=1 SCAR=0.0
26 120 ▶ sub get_exp {
Subroutine get_exp: called CC=2 SCAR=7.1
Pod undocumented
27 120 my ($tag) = @_;
28 120 ▶ return unless defined $tag;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag 0 120 120
29 120 return qr|<$tag>[^<]+</$tag>\s*|;
30 }
31  
32 10 $NUM = get_exp('cd');
33 10 $GER = get_exp('vbg');
34 10 $ADJ = get_exp('jj[rs]*');
35 10 $PART = get_exp('vbn');
36 10 $NN = get_exp('nn[sp]*');
37 10 $NNP = get_exp('nnp');
38 10 $PREP = get_exp('in');
39 10 $DET = get_exp('det');
40 10 $PAREN= get_exp('[lr]rb');
41 10 $QUOT = get_exp('ppr');
42 10 $SEN = get_exp('pp');
43 10 $WORD = get_exp('\p{IsWord}+');
44  
45 10 ($lexpath) = __FILE__ =~ /(.*)\.pm/;
46 10 $word_path = File::Spec->catfile($lexpath, 'pos_words.hash');
47 10 $tag_path = File::Spec->catfile($lexpath, 'pos_tags.hash');
48  
49 10 memoize(\&Lingua::EN::Tagger::stem,
50 TIE => [ 'Memoize::ExpireLRU',
51 CACHESIZE => 1000,
52 ]);
53  
54 10 memoize(\&Lingua::EN::Tagger::_assign_tag,
55 TIE => ['Memoize::ExpireLRU',
56 CACHESIZE => 10000,
57 ]);
58 }
59  
60  
61 ######################################################################
62  
63 =head1 NAME
64  
65 Lingua::EN::Tagger - Part-of-speech tagger for English natural language processing.
66  
67  
68 =head1 SYNOPSIS
69  
70 # Create a parser object
71 my $p = new Lingua::EN::Tagger;
72  
73 # Add part of speech tags to a text
74 my $tagged_text = $p->add_tags($text);
75  
76 ...
77  
78 # Get a list of all nouns and noun phrases with occurrence counts
79 my %word_list = $p->get_words($text);
80  
81 ...
82  
83 # Get a readable version of the tagged text
84 my $readable_text = $p->get_readable($text);
85  
86  
87 =head1 DESCRIPTION
88  
89 The module is a probability based, corpus-trained tagger that assigns POS tags to
90 English text based on a lookup dictionary and a set of probability values. The tagger
91 assigns appropriate tags based on conditional probabilities - it examines the
92 preceding tag to determine the appropriate tag for the current word.
93 Unknown words are classified according to word morphology or can be set to
94 be treated as nouns or other parts of speech.
95  
96 The tagger also extracts as many nouns and noun phrases as it can, using a
97 set of regular expressions.
98  
99 =head1 CONSTRUCTOR
100  
101 =over
102  
103  
104 =item new %PARAMS
105  
106 Class constructor. Takes a hash with the following parameters (shown with default
107 values):
108  
109 =over
110  
111 =item unknown_word_tag => ''
112  
113 Tag to assign to unknown words
114  
115 =item stem => 0
116  
117 Stem single words using Lingua::Stem::EN
118  
119 =item weight_noun_phrases => 0
120  
121 When returning occurrence counts for a noun phrase, multiply the value
122 by the number of words in the NP.
123  
124 =item longest_noun_phrase => 5
125  
126 Will ignore noun phrases longer than this threshold. This affects
127 only the get_words() and get_nouns() methods.
128  
129 =item relax => 0
130  
131 Relax the Hidden Markov Model: this may improve accuracy for
132 uncommon words, particularly words used polysemously
133  
134 =back
135  
136 =cut
137  
138 ######################################################################
139  
140 10 ▶sub new {
Subroutine new: called CC=4 SCAR=15.4
Pod documented
141 10 my ($class, %params) = @_;
142 10 my $self = {unknown_word_tag => '',
143 stem => 0,
144 weight_noun_phrases => 0,
145 longest_noun_phrase => 5,
146 lc => 1,
147 tag_lex => 'tags.yml',
148 word_lex => 'words.yml',
149 unknown_lex => 'unknown.yml',
150 word_path => $word_path,
151 tag_path => $tag_path,
152 relax => 0,
153 debug => 0,
154 %params};
155  
156 10 bless $self, $class;
157  
158 10 ▶ unless (-f $self->{'word_path'} and -f $self->{'tag_path'}){
Branch: 1 branch
BranchTrueFalseTotal
if (-f $self->{'word_path'} and -f $self->{'tag_path'}) { } 10 0 10
Condition33%1/3
-f $self->{"word_path"} and -f $self->{"tag_path"}
!ll&&!rl&&r
0010
MC/DC0%0/2
-f $self->{"word_path"} and -f $self->{"tag_path"}
-f $self->{"word_path"} -f $self->{"tag_path"}
Truth table33%1/3
A and B
A= -f $self->{"word_path"}B= -f $self->{"tag_path"}
ABresult
0X0
100
111
159 0 ▶ carp "Couldn't locate POS lexicon, creating new one" if $self->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
160 0 $self->install();
161 } else {
162 10 %_LEXICON = %{retrieve($self->{'word_path'})}; # A hash of words and corresponding parts of speech
163 10 %_HMM = %{retrieve($self->{'tag_path'})}; # A hash of adjacent part of speech tags and the probability of each
164 }
165  
166 10 $MNP = $self->_get_max_noun_regex();
167 10 $self->_reset();
168  
169 10 return $self;
170 }
171  
172 ######################################################################
173  
174 =back
175  
176 =head1 METHODS
177  
178 =over
179  
180 =item add_tags TEXT
181  
182 Examine the string provided and return it fully tagged (XML style)
183  
184 =cut
185  
186 ######################################################################
187 36 ▶sub add_tags {
Subroutine add_tags: called CC=1 SCAR=0.0
Pod documented
188 36 my ($self, $text) = @_;
189  
190 36 my $tags = $self->add_tags_incrementally($text);
191 36 $self->_reset;
192 36 return $tags;
193 }
194  
195 ######################################################################
196  
197 =item add_tags_incrementally TEXT
198  
199 Examine the string provided and return it fully tagged (XML style) but
200 do not reset the internal part-of-speech state between invocations.
201  
202 =cut
203  
204 ######################################################################
205 36 ▶sub add_tags_incrementally {
Subroutine add_tags_incrementally: called CC=4 SCAR=13.9
Pod documented
206 36 my ($self, $text) = @_;
207  
208 36 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 8 28 36
209  
210 28 my @text = $self->_clean_text($text);
211 28 my $t = $self->{'current_tag'}; # shortcut
212 my (@tags) =
213 map {
214 28 $t = $self->_assign_tag($t, $self->_clean_word($_))
215 1966 ▶ || $self->{'unknown_word_tag'} || 'nn';
Condition80%4/5
$self->_assign_tag($t, $self->_clean_word($_)) || $self->{'unknown_word_tag'} || 'nn'
l!l
195412
$self->_assign_tag($t, $self->_clean_word($_)) or $self->{"unknown_word_tag"}
l!l&&r!l&&!r
1954012
MC/DC50%1/2
$self->_assign_tag($t, $self->_clean_word($_)) || $self->{'unknown_word_tag'} || 'nn'
$self->_assign_tag($t, $self->_clean_word($_)) $self->{"unknown_word_tag"}
Truth table66%2/3
A or B
A= $self->_assign_tag($t, $self->_clean_word($_))B= $self->{"unknown_word_tag"}
ABresult
1X1
011
000
216 1966 "<$t>$_</$t>"
217 } @text;
218 28 $self->{'current_tag'} = $t;
219 28 return join ' ', @tags;
220 }
221  
222 ######################################################################
223  
224 =item get_words TEXT
225  
226 Given a text string, return as many nouns and
227 noun phrases as possible. Applies L<add_tags> and involves three stages:
228  
229 =over
230  
231 * Tag the text
232 * Extract all the maximal noun phrases
233 * Recursively extract all noun phrases from the MNPs
234  
235 =back
236  
237 =cut
238  
239 ######################################################################
240 2 ▶sub get_words {
Subroutine get_words: called CC=3 SCAR=11.8
Pod documented
241 2 my ($self, $text) = @_;
242  
243 2 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 2 2
244  
245 2 my $tagged = $self->add_tags($text);
246  
247 2 ▶ if($self->{'longest_noun_phrase'} <= 1){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'longest_noun_phrase'} <= 1) { } 0 2 2
248 0 return $self->get_nouns($tagged);
249 } else {
250 2 return $self->get_noun_phrases($tagged);
251 }
252 }
253  
254  
255 ######################################################################
256  
257 =item get_readable TEXT
258  
259 Return an easy-on-the-eyes tagged version of a text string. Applies
260 L<add_tags> and reformats to be easier to read.
261  
262 =cut
263  
264 ######################################################################
265 15 ▶sub get_readable {
Subroutine get_readable: called CC=2 SCAR=7.0
Pod documented
266 15 my ($self, $text) = @_;
267  
268 15 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 15 15
269  
270 15 my $tagged = $self->add_tags($text);
271 15 $tagged =~ s/<\p{IsLower}+>([^<]+)<\/(\p{IsLower}+)>/$1\/\U$2/go;
272 15 return $tagged;
273 }
274  
275  
276 ######################################################################
277  
278 =item get_sentences TEXT
279  
280 Returns an anonymous array of sentences (without POS tags) from a text.
281  
282 =cut
283  
284 ######################################################################
285 1 ▶sub get_sentences {
Subroutine get_sentences: called CC=3 SCAR=11.0
Pod documented
286 1 my ($self, $text) = @_;
287  
288 1 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 1 1
289 1 my $tagged = $self->add_tags($text);
290 1 my @sentences;
291 {
292 1 local $self->{'lc'};
293 1 $self->{'lc'} = 0;
294 1 @sentences = map {$self->_strip_tags($_)}
295 split /<\/pp>/, $tagged;
296 }
297  
298 1 foreach (@sentences){
299 8 s/ ('s?) /$1 /g;
300 8 s/ ([\$\(\[\{]) / $1/g;
301 8 s/ (\P{IsWord}+) /$1 /g;
302 8 s/ (`+) / $1/g;
303 8 s/ (\P{IsWord}+)$/$1/;
304 8 s/^(`+) /$1/;
305 8 s/^([\$\(\[\{]) /$1/g;
306 }
307 1 return \@sentences;
308 }
309  
310  
311 ###########################################
312 # _valid_text TEXT
313 #
314 # Check whether the text is a valid string
315 ###########################################
316 448 ▶sub _valid_text {
Subroutine _valid_text: called CC=6 SCAR=19.9
317 448 my ($self, $text) = @_;
318 448 ▶ if(!defined $text){
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $text) { } 4 444 448
elsif (ref $text) { } 0 444 444
elsif ($text =~ /^\s*$/) { } 4 440 444
319 # $text is undefined, nothing to parse
320 4 ▶ carp "method call on uninitialized variable" if $self->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 4 4
321 4 return undef;
322 } elsif (ref $text){
323 # $text is a scalar reference, don't parse
324 0 ▶ carp "method call on a scalar reference" if $self->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
325 0 return undef;
326 } elsif ($text =~ /^\s*$/){
327 # $text is defined as an empty string, nothing to parse
328 4 return undef;
329 } else {
330 # $text is valid
331 440 return 1;
332 }
333 }
334  
335  
336 0 ▶sub lower_case {
Subroutine lower_case: not called CC=2 SCAR=17.9
Pod undocumented
337 0 my ($self, $lc) = @_;
338 0 ▶ if($lc){
Branch: 1 branch
BranchTrueFalseTotal
if ($lc) { } 0 0 0
339 0 $self->{'lc'} = 1;
340 } else {
341 0 $self->{'lc'} = 0;
342 }
343 }
344  
345 #####################################################################
346 # _strip_tags TEXT
347 #
348 # Return a text string with the XML-style part-of-speech tags removed.
349 #####################################################################
350 355 ▶sub _strip_tags {
Subroutine _strip_tags: called CC=3 SCAR=11.0
351 355 my ($self, $text) = @_;
352 355 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 355 355
353  
354 355 $text =~ s/<[^>]+>//gs;
355 355 $text =~ s/\s+/ /gs;
356 355 $text =~ s/^\s*//;
357 355 $text =~ s/\s*$//;
358 355 ▶ if($self->{'lc'}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'lc'}) { } 347 8 355
359 347 return lc($text);
360 } else {
361 8 return $text;
362 }
363 }
364  
365  
366 #####################################################################
367 # _clean_text TEXT
368 #
369 # Strip the provided text of HTML-style tags and separate off
370 # any punctuation in preparation for tagging
371 #####################################################################
372 30 ▶sub _clean_text {
Subroutine _clean_text: called CC=3 SCAR=11.2
373 30 my ($self, $text) = @_;
374 30 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 30 30
375  
376 # Strip out any markup and convert entities to their proper form
377 30 my $html_parser;
378 30 utf8::decode($text);
379 30 $html_parser = HTML::TokeParser->new(\$text);
380  
381 30 my $cleaned_text = $html_parser->get_text;
382 30 ▶ while($html_parser->get_token){
Branch: 1 branch
BranchTrueFalseTotal
if ($html_parser->get_token) 0 30 30
383 0 $cleaned_text .= ($html_parser->get_text)." ";
384 }
385  
386 # Tokenize the text (splitting on punctuation as you go)
387 30 my @tokenized = map {$self->_split_punct($_)}
388 split /\s+/, $cleaned_text;
389 30 my @words = $self->_split_sentences(\@tokenized);
390 30 return @words;
391 }
392  
393  
394 #####################################################################
395 # _split_sentences ARRAY_REF
396 #
397 # This handles all of the trailing periods, keeping those that
398 # belong on abbreviations and removing those that seem to be
399 # at the end of sentences. This method makes some assumptions
400 # about the use of capitalization in the incoming text
401 #####################################################################
402 36 ▶sub _split_sentences {
Subroutine _split_sentences: called CC=10 SCAR=23.0
403 36 my ($self, $array_ref) = @_;
404 36 my @tokenized = @{$array_ref};
405  
406 36 my @PEOPLE = qw/jr mr ms mrs dr prof esq sr sen sens rep reps gov attys attys supt det mssrs rev/;
407 36 my @ARMY = qw/col gen lt cmdr adm capt sgt cpl maj brig/;
408 36 my @INST = qw/dept univ assn bros ph.d/;
409 36 my @PLACE = qw/arc al ave blvd bld cl ct cres exp expy dist mt mtn ft fy fwy hwy hway la pde pd plz pl rd st tce/;
410 36 my @COMP = qw/mfg inc ltd co corp/;
411 36 my @STATE = qw/ala ariz ark cal calif colo col conn del fed fla ga ida id ill ind ia kans kan ken ky la me md is mass mich minn miss mo mont neb nebr nev mex okla ok ore penna penn pa dak tenn tex ut vt va wash wis wisc wy wyo usafa alta man ont que sask yuk/;
412 36 my @MONTH = qw/jan feb mar apr may jun jul aug sep sept oct nov dec/;
413 36 my @MISC = qw/vs etc no esp/;
414 36 my %ABBR = map {$_, 0}
415 (@PEOPLE, @ARMY, @INST, @PLACE, @COMP, @STATE, @MONTH, @MISC);
416  
417 36 my @words;
418 36 for(0 .. $#tokenized){
419 2052 ▶ if (defined $tokenized[$_ + 1]
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tokenized[$_ + 1] and $tokenized[$_ + 1] =~ /[\p{IsUpper}\W]/ and $tokenized[$_] =~ /^(.+)\.$/) 79 1973 2052
Condition100%6/6
defined $tokenized[$_ + 1] and $tokenized[$_ + 1] =~ /[\p{IsUpper}\W]/ and $tokenized[$_] =~ /^(.+)\.$/
!ll&&!rl&&r
145352079
defined $tokenized[$_ + 1] and $tokenized[$_ + 1] =~ /[\p{IsUpper}\W]/
!ll&&!rl&&r
361417599
MC/DC100%3/3
defined $tokenized[$_ + 1] and $tokenized[$_ + 1] =~ /[\p{IsUpper}\W]/ and $tokenized[$_] =~ /^(.+)\.$/
defined $tokenized[$_ + 1] $tokenized[$_ + 1] =~ /[\p{IsUpper}\W]/ $tokenized[$_] =~ /^(.+)\.$/
Truth table100%4/4
A and B and C
A= defined $tokenized[$_ + 1]B= $tokenized[$_ + 1] =~ /[\p{IsUpper}\W]/C= $tokenized[$_] =~ /^(.+)\.$/
ABCresult
0XX0
10X0
1100
1111
420 and $tokenized[$_ + 1] =~ /[\p{IsUpper}\W]/
421 and $tokenized[$_] =~ /^(.+)\.$/){
422  
423 # Don't separate the period off words that
424 # meet any of the following conditions:
425 # 1. It is defined in one of the lists above
426 # 2. It is only one letter long: Alfred E. Sloan
427 # 3. It has a repeating letter-dot: U.S.A. or J.C. Penney
428 79 ▶ unless(defined $ABBR{lc $1}
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ABBR{lc $1} or $1 =~ /^\p{IsLower}$/i or $1 =~ /^\p{IsLower}(?:\.\p{IsLower})+$/i) 59 20 79
Condition100%6/6
defined $ABBR{lc $1} or $1 =~ /^\p{IsLower}$/i or $1 =~ /^\p{IsLower}(?:\.\p{IsLower})+$/i
l!l&&r!l&&!r
19159
defined $ABBR{lc $1} or $1 =~ /^\p{IsLower}$/i
l!l&&r!l&&!r
18160
MC/DC100%3/3
defined $ABBR{lc $1} or $1 =~ /^\p{IsLower}$/i or $1 =~ /^\p{IsLower}(?:\.\p{IsLower})+$/i
defined $ABBR{lc $1} $1 =~ /^\p{IsLower}$/i $1 =~ /^\p{IsLower}(?:\.\p{IsLower})+$/i
Truth table100%4/4
A or B or C
A= defined $ABBR{lc $1}B= $1 =~ /^\p{IsLower}$/iC= $1 =~ /^\p{IsLower}(?:\.\p{IsLower})+$/i
ABCresult
1XX1
01X1
0011
0000
429 or $1 =~ /^\p{IsLower}$/i
430 or $1 =~ /^\p{IsLower}(?:\.\p{IsLower})+$/i){
431 59 push @words, ($1, '.');
432 59 next;
433 }
434 }
435 1993 push @words, $tokenized[$_];
436 }
437  
438 # If the final word ends in a period...
439 36 ▶ if(defined $words[$#words] and $words[$#words] =~ /^(.*\p{IsWord})\.$/){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $words[$#words] and $words[$#words] =~ /^(.*\p{IsWord})\.$/) 7 29 36
Condition66%2/3
defined $words[$#words] and $words[$#words] =~ /^(.*\p{IsWord})\.$/
!ll&&!rl&&r
0297
MC/DC50%1/2
defined $words[$#words] and $words[$#words] =~ /^(.*\p{IsWord})\.$/
defined $words[$#words] $words[$#words] =~ /^(.*\p{IsWord})\.$/
Truth table66%2/3
A and B
A= defined $words[$#words]B= $words[$#words] =~ /^(.*\p{IsWord})\.$/
ABresult
0X0
100
111
440 7 $words[$#words] = $1;
441 7 push @words, '.';
442 }
443  
444 36 return @words;
445 }
446  
447  
448 ###########################################################################
449 # _split_punct TERM
450 #
451 # Separate punctuation from words, where appropriate. This leaves trailing
452 # periods in place to be dealt with later. Called by the _clean_text method.
453 ###########################################################################
454 1799 ▶sub _split_punct {
Subroutine _split_punct: called CC=2 SCAR=6.9
455 1799 local $_ = $_[1];
456  
457 # If there's no punctuation, return immediately
458 1799 ▶ return $_ if /^\p{IsWord}+$/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\p{IsWord}+$/ 1427 372 1799
459  
460 # Sanity checks
461 372 s/\W{10,}/ /og; # get rid of long trails of non-word characters
462  
463 # Put quotes into a standard format
464 372 s/`(?!`)(?=.*\p{IsWord})/` /og; # Shift left quotes off text
465 372 s/"(?=.*\p{IsWord})/ `` /og; # Convert left quotes to ``
466 372 s/(?<![\p{IsWord}\s'])'(?=.*\p{IsWord})/ ` /go; # Convert left quotes to `
467 372 s/"/ '' /og; # Convert (remaining) quotes to ''
468 372 s/(?<=\p{IsWord})'(?!')(?=\P{IsWord}|$)/ ' /go; # Separate right single quotes
469  
470 # Handle all other punctuation
471 372 s/--+/ - /go; # Convert and separate dashes
472 372 s/,(?!\p{IsDigit})/ , /go; # Shift commas off everything but numbers
473 372 s/:$/ :/go; # Shift semicolons off
474 372 s/(\.\.\.+)/ $1 /; # Shift ellipses off
475 372 s/([\(\[\{\}\]\)])/ $1 /go; # Shift off brackets
476 372 s/([\!\?#\$%;~|])/ $1 /go; # Shift off other ``standard'' punctuation
477  
478 # English-specific contractions
479 372 s/(?<=\p{IsAlpha})'([dms])\b/ '$1/go; # Separate off 'd 'm 's
480 372 s/n't\b/ n't/go; # Separate off n't
481 372 s/'(ve|ll|re)\b/ '$1/go; # Separate off 've, 'll, 're
482  
483 372 return split;
484 }
485  
486  
487 #####################################################################
488 # _assign_tag TAG, WORD (memoized)
489 #
490 # Given a preceding tag TAG, assign a tag to WORD.
491 # Called by the choose_tag method.
492 # This subroutine is a modified version of the Viterbi algorithm
493 # for part of speech tagging
494 #####################################################################
495 1966 ▶sub _assign_tag {
Subroutine _assign_tag: called CC=9 SCAR=22.1
496 1966 my ($self, $prev_tag, $word) = @_;
497  
498 1966 ▶ if ($self->{'unknown_word_tag'} and $word eq "-unknown-"){
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'unknown_word_tag'} and $word eq '-unknown-') { } 0 1966 1966
elsif ($word eq '-sym-') { } 8 1958 1966
Condition33%1/3
$self->{"unknown_word_tag"} and $word eq "-unknown-"
!ll&&!rl&&r
196600
MC/DC0%0/2
$self->{"unknown_word_tag"} and $word eq "-unknown-"
$self->{"unknown_word_tag"} $word eq "-unknown-"
Truth table33%1/3
A and B
A= $self->{"unknown_word_tag"}B= $word eq "-unknown-"
ABresult
0X0
100
111
499 # If the 'unknown_word_tag' value is defined,
500 # classify unknown words accordingly
501 0 return $self->{'unknown_word_tag'};
502 } elsif ($word eq "-sym-"){
503 # If this is a symbol, tag it as a symbol
504 8 return "sym";
505 }
506  
507 1958 my $best_so_far = 0;
508  
509 1958 my $w = $_LEXICON{$word};
510 1958 my $t = \%_HMM;
511  
512 ##############################################################
513 # TAG THE TEXT
514 # What follows is a modified version of the Viterbi algorithm
515 # which is used in most POS taggers
516 ##############################################################
517 1958 my $best_tag;
518  
519 1958 foreach my $tag (keys %{$t->{$prev_tag}}){
520 # With the $self->{'relax'} var set, this method
521 # will also include any `open classes' of POS tags
522 79164 my $pw;
523 79164 ▶ if(defined ${$w->{$tag}}){
Branch: 2 branches
BranchTrueFalseTotal
if (defined ${$$w{$tag};}) { } 4799 74365 79164
elsif ($self->{'relax'} and $tag =~ /^(?:jj|nn|rb|vb)/) { } 2119 72246 74365
524 4799 $pw = ${$w->{$tag}};
525 ▶ } elsif ($self->{'relax'} and $tag =~ /^(?:jj|nn|rb|vb)/){
Condition100%3/3
$self->{"relax"} and $tag =~ /^(?:jj|nn|rb|vb)/
!ll&&!rl&&r
6864935972119
MC/DC100%2/2
$self->{"relax"} and $tag =~ /^(?:jj|nn|rb|vb)/
$self->{"relax"} $tag =~ /^(?:jj|nn|rb|vb)/
Truth table100%3/3
A and B
A= $self->{"relax"}B= $tag =~ /^(?:jj|nn|rb|vb)/
ABresult
0X0
100
111
526 2119 $pw = 0;
527 } else {
528 72246 next;
529 }
530  
531 # Bayesian logic:
532 # P = P($tag | $prev_tag) * P($tag | $word)
533 6918 my $probability = $t->{$prev_tag}{$tag} * ($pw + 1);
534  
535 # Set the tag with maximal probability
536 6918 ▶ if($probability > $best_so_far) {
Branch: 1 branch
BranchTrueFalseTotal
if ($probability > $best_so_far) 3180 3738 6918
537 3180 $best_so_far = $probability;
538 3180 $best_tag = $tag;
539 }
540 }
541  
542 1958 return $best_tag;
543 }
544  
545  
546 ############################################################################
547 # _reset
548 #
549 # this subroutine will reset the preceding tag to a sentence ender (PP).
550 # This prepares the first word of a new sentence to be tagged correctly.
551 ############################################################################
552 46 ▶sub _reset {
Subroutine _reset: called CC=1 SCAR=0.0
553 46 my ($self) = @_;
554 46 $self->{'current_tag'} = 'pp';
555 }
556  
557  
558 #####################################################################
559 # _clean_word WORD
560 #
561 # This subroutine determines whether a word should be considered in its
562 # lower or upper case form. This is useful in considering proper nouns
563 # and words that begin sentences. Called by L<choose_tag>.
564 #####################################################################
565 1966 ▶sub _clean_word {
Subroutine _clean_word: called CC=3 SCAR=11.3
566 1966 my ($self, $word) = @_;
567  
568 1966 ▶ if (defined $_LEXICON{$word}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $Lingua::EN::Tagger::_LEXICON{$word}) { } 1823 143 1966
elsif (defined $Lingua::EN::Tagger::_LEXICON{lcfirst $word}) { } 0 143 143
569 # seen this word as it appears (lower or upper case)
570 1823 return $word;
571  
572 } elsif (defined $_LEXICON{lcfirst $word}) {
573 # seen this word only as lower case
574 0 return lcfirst $word;
575  
576 } else {
577 # never seen this word. guess.
578 143 return $self->_classify_unknown_word($word);
579 }
580 }
581  
582  
583 #####################################################################
584 # _classify_unknown_word WORD
585 #
586 # This changes any word not appearing in the lexicon to identifiable
587 # classes of words handled by a simple unknown word classification
588 # metric. Called by the _clean_word method.
589 #####################################################################
590 143 ▶sub _classify_unknown_word {
Subroutine _classify_unknown_word: called CC=17 SCAR=30.3
591 143 my ($self, $word) = @_;
592  
593 143 local $_ = $word;
594  
595 143 ▶ if(m/[\(\{\[]/){ # Left brackets
Branch: 14 branches
BranchTrueFalseTotal
if (/[\(\{\[]/) { } 14 129 143
elsif (/[\)\]\}]/o) { } 14 115 129
elsif (/^-?(?:\p{IsDigit}+(?:\.\p{IsDigit}*)?|\.\p{IsDigit}+)$/) { } 6 109 115
elsif (m[^\p{IsDigit}+[\p{IsDigit}/:-]+\p{IsDigit}$]) { } 0 109 109
elsif (/^-?\p{IsDigit}+\p{IsWord}+$/o) { } 0 109 109
elsif (/^\p{IsUpper}[\p{IsUpper}\.-]*$/o) { } 0 109 109
elsif (/\p{IsWord}-\p{IsWord}/o) { } 21 88 109
elsif (/^\W+$/o) { } 8 80 88
elsif ($_ eq ucfirst $_) { } 20 60 80
elsif (/ing$/o) { } 10 50 60
elsif (/s$/o) { } 16 34 50
elsif (/tion$/o) { } 0 34 34
elsif (/ly$/o) { } 0 34 34
elsif (/ed$/o) { } 0 34 34
596 14 $word = "*LRB*";
597  
598 } elsif(m/[\)\]\}]/o){ # Right brackets
599 14 $word = "*RRB*";
600  
601 } elsif (m/^-?(?:\p{IsDigit}+(?:\.\p{IsDigit}*)?|\.\p{IsDigit}+)$/){ # Floating point number
602 6 $word = "*NUM*";
603  
604 } elsif (m/^\p{IsDigit}+[\p{IsDigit}\/:-]+\p{IsDigit}$/){ # Other number constructs
605 0 $word = "*NUM*";
606  
607 } elsif (m/^-?\p{IsDigit}+\p{IsWord}+$/o){ # Ordinal number
608 0 $word = "*ORD*";
609  
610 } elsif (m/^\p{IsUpper}[\p{IsUpper}\.-]*$/o) { # Abbreviation (all caps)
611 0 $word = "-abr-";
612  
613 } elsif (m/\p{IsWord}-\p{IsWord}/o){ # Hyphenated word
614 21 my ($h_suffix) = m/-([^-]+)$/;
615  
616 21 ▶ if ($h_suffix and defined ${$_LEXICON{$h_suffix}{'jj'} }){
Branch: 1 branch
BranchTrueFalseTotal
if ($h_suffix and defined ${$Lingua::EN::Tagger::_LEXICON{$h_suffix}{'jj'};}) { } 10 11 21
Condition66%2/3
$h_suffix and defined ${$Lingua::EN::Tagger::_LEXICON{$h_suffix}{"jj"};}
!ll&&!rl&&r
01110
MC/DC50%1/2
$h_suffix and defined ${$Lingua::EN::Tagger::_LEXICON{$h_suffix}{"jj"};}
$h_suffix defined ${$Lingua::EN::Tagger::_LEXICON{$h_suffix}{"jj"};}
Truth table66%2/3
A and B
A= $h_suffixB= defined ${$Lingua::EN::Tagger::_LEXICON{$h_suffix}{"jj"};}
ABresult
0X0
100
111
617 # last part of this is defined as an adjective
618 10 $word = "-hyp-adj-";
619 } else {
620 # last part of this is not defined as an adjective
621 11 $word = "-hyp-";
622 }
623  
624 } elsif (m/^\W+$/o){ # Symbol
625 8 $word = "-sym-";
626  
627 } elsif ($_ eq ucfirst) { # Capitalized word
628 20 $word = "-cap-";
629  
630 } elsif (m/ing$/o) { # Ends in 'ing'
631 10 $word = "-ing-";
632  
633 } elsif(m/s$/o) { # Ends in 's'
634 16 $word = "-s-";
635  
636 } elsif (m/tion$/o){ # Ends in 'tion'
637 0 $word = "-tion-";
638  
639 } elsif (m/ly$/o){ # Ends in 'ly'
640 0 $word = "-ly-";
641  
642 } elsif (m/ed$/o){ # Ends in 'ed'
643 0 $word = "-ed-";
644  
645 } else { # Completely unknown
646 34 $word = "-unknown-";
647 }
648  
649 143 return $word;
650 }
651  
652  
653 #####################################################################
654 # stem WORD (memoized)
655 #
656 # Returns the word stem as given by L<Lingua::Stem::EN>. This can be
657 # turned off with the class parameter 'stem' => 0.
658 #####################################################################
659 236 ▶sub stem {
Subroutine stem: called CC=2 SCAR=6.9
Pod documented
660 236 my ($self, $word) = @_;
661 236 ▶ return $word unless $self->{'stem'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stem"} 232 4 236
662  
663 4 my $stemref = Lingua::Stem::En::stem(-words => [ $word ]);
664 4 return $stemref->[0];
665 }
666  
667  
668 #####################################################################
669 # _get_max_noun_regex
670 #
671 # This returns a compiled regex for extracting maximal noun phrases
672 # from a POS-tagged text.
673 #####################################################################
674 10 ▶sub _get_max_noun_regex {
Subroutine _get_max_noun_regex: called CC=1 SCAR=0.0
675 10 my $regex = qr/
676 (?:$NUM)?(?:$GER|$ADJ|$PART)* # optional number, gerund - adjective -participle
677 (?:$NN)+ # Followed by one or more nouns
678 (?:
679 (?:$PREP)*(?:$DET)?(?:$NUM)? # Optional preposition, determinant, cardinal
680 (?:$GER|$ADJ|$PART)* # Optional gerund-adjective -participle
681 (?:$NN)+ # one or more nouns
682 )*
683 /xo;
684 10 return $regex;
685 }
686  
687  
688 ######################################################################
689  
690 =item get_proper_nouns TAGGED_TEXT
691  
692 Given a POS-tagged text, this method returns a hash of all proper nouns
693 and their occurrence frequencies. The method is greedy and will
694 return multi-word phrases, if possible, so it would find ``Linguistic
695 Data Consortium'' as a single unit, rather than as three individual
696 proper nouns. This method does not stem the found words.
697  
698 =cut
699  
700 ######################################################################
701 1 ▶sub get_proper_nouns {
Subroutine get_proper_nouns: called CC=8 SCAR=21.6
Pod documented
702 1 my ($self, $text) = @_;
703  
704 1 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 1 1
705  
706 1 my @trimmed = map {$self->_strip_tags($_)}
707 ($text =~ /($NNP+)/gs);
708 1 my %nnp;
709 1 foreach my $n (@trimmed) {
710 4 ▶ next unless length($n) < 100; # sanity check on word length
Branch: 1 branch
BranchTrueFalseTotal
unless length $n < 100 0 4 4
711 4 ▶ $nnp{$n}++ unless $n =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $n =~ /^\s*$/ 4 0 4
712 }
713  
714  
715 # Now for some fancy resolution stuff...
716 1 foreach (keys %nnp){
717 4 my @words = split /\s/;
718  
719 # Let's say this is an organization's name --
720 # (and it's got at least three words)
721 # is there a corresponding acronym in this hash?
722 4 ▶ if (scalar @words > 2){
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @words > 2) 1 3 4
723 # Make a (naive) acronym out of this name
724 1 my $acronym = join '', map{/^(\p{IsWord})\p{IsWord}*$/} @words;
725 1 ▶ if (defined $nnp{$acronym}){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $nnp{$acronym}) 0 1 1
726 # If that acronym has been seen,
727 # remove it and add the values to
728 # the full name
729 0 $nnp{$_} += $nnp{$acronym};
730 0 delete $nnp{$acronym};
731 }
732 }
733 }
734  
735 1 return %nnp;
736 }
737  
738  
739 ######################################################################
740  
741 =item get_nouns TAGGED_TEXT
742  
743 Given a POS-tagged text, this method returns all nouns and their
744 occurrence frequencies.
745  
746 =cut
747  
748 ######################################################################
749 2 ▶sub get_nouns {
Subroutine get_nouns: called CC=5 SCAR=16.4
Pod documented
750 2 my ($self, $text) = @_;
751  
752 2 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 2 2
753  
754 2 my @trimmed = map {$self->_strip_tags($_)}
755 ($text =~ /($NN)/gs);
756  
757 2 my %return;
758 2 foreach my $n (@trimmed) {
759 80 $n = $self->stem($n);
760 80 ▶ next unless length($n) < 100; # sanity check on word length
Branch: 1 branch
BranchTrueFalseTotal
unless length $n < 100 0 80 80
761 80 ▶ $return{$n}++ unless $n =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $n =~ /^\s*$/ 80 0 80
762 }
763  
764 2 return %return;
765 }
766  
767  
768 ######################################################################
769  
770 =item get_max_noun_phrases TAGGED_TEXT
771  
772 Given a POS-tagged text, this method returns only the maximal noun phrases.
773 May be called directly, but is also used by L<get_noun_phrases>
774  
775 =cut
776  
777 ######################################################################
778 2 ▶sub get_max_noun_phrases {
Subroutine get_max_noun_phrases: called CC=5 SCAR=16.2
Pod documented
779 2 my ($self, $text) = @_;
780  
781 2 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 2 2
782  
783 2 my @mn_phrases = map {$self->_strip_tags($_)}
784 ($text =~ /($MNP)/gs);
785  
786 2 my %return;
787 2 foreach my $p (@mn_phrases) {
788 42 ▶ $p = $self->stem($p)
Branch: 1 branch
BranchTrueFalseTotal
unless $p =~ /\s/ 16 26 42
789 unless $p =~ /\s/; # stem single words
790 42 ▶ $return{$p}++ unless $p =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $p =~ /^\s*$/ 42 0 42
791 }
792  
793 2 return %return;
794 }
795  
796  
797 ######################################################################
798  
799 =item get_noun_phrases TAGGED_TEXT
800  
801 Similar to get_words, but requires a POS-tagged text as an argument.
802  
803 =cut
804  
805 ######################################################################
806 4 ▶sub get_noun_phrases {
Subroutine get_noun_phrases: called CC=11 SCAR=24.0
Pod documented
807 4 my ($self, $text) = @_;
808  
809 4 ▶ return unless $self->_valid_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_valid_text($text) 0 4 4
810  
811 4 my $found;
812 4 my $phrase_ext = qr/(?:$PREP|$DET|$NUM)+/xo;
813  
814 # Find MNPs in the text, one sentence at a time
815 # Record and split if the phrase is extended by a (?:$PREP|$DET|$NUM)
816 4 ▶ my @mn_phrases = map {$found->{$_}++ if m/$phrase_ext/; split /$phrase_ext/}
Branch: 1 branch
BranchTrueFalseTotal
if /$phrase_ext/ 20 64 84
817 ($text =~ /($MNP)/gs);
818  
819 4 foreach(@mn_phrases){
820 # Split the phrase into an array of words, and
821 # create a loop for each word, shortening the
822 # phrase by removing the word in the first position
823 # Record the phrase and any single nouns that are found
824 124 my @words = split;
825  
826 124 for(0 .. $#words){
827 188 ▶ $found->{join(" ", @words)}++ if scalar @words > 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @words > 1 64 124 188
828 188 my $w = shift @words;
829 188 ▶ $found->{$w}++ if $w =~ /$NN/;
Branch: 1 branch
BranchTrueFalseTotal
if $w =~ /$Lingua::EN::Tagger::NN/ 160 28 188
830 }
831 }
832  
833 4 my %return;
834 4 foreach(keys %{$found}){
835 220 my $k = $self->_strip_tags($_);
836 220 my $v = $found->{$_};
837  
838 # We weight by the word count to favor long noun phrases
839 220 my @space_count = $k =~ /\s+/go;
840 220 my $word_count = scalar @space_count + 1;
841  
842 # Throttle MNPs if necessary
843 220 ▶ next if $word_count > $self->{'longest_noun_phrase'};
Branch: 1 branch
BranchTrueFalseTotal
if $word_count > $self->{"longest_noun_phrase"} 0 220 220
844  
845 220 ▶ $k = $self->stem($k) unless $word_count > 1; # stem single words
Branch: 1 branch
BranchTrueFalseTotal
unless $word_count > 1 136 84 220
846 220 my $multiplier = 1;
847 220 ▶ $multiplier = $word_count if $self->{'weight_noun_phrases'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"weight_noun_phrases"} 110 110 220
848 220 $return{$k} += ($multiplier * $v);
849 }
850  
851 4 return %return;
852 }
853  
854  
855 ######################################################################
856  
857 =item install
858  
859 Reads some included corpus data and saves it in a stored hash on the
860 local file system. This is called automatically if the tagger can't
861 find the stored lexicon.
862  
863 =cut
864  
865 ######################################################################
866 0 ▶sub install {
Subroutine install: not called CC=2 SCAR=17.9
Pod documented
867 0 my ($self) = @_;
868  
869 0 ▶ carp "Creating part-of-speech lexicon" if $self->{'debug'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
870 0 $self->_load_tags($self->{'tag_lex'});
871 0 $self->_load_words($self->{'word_lex'});
872 0 $self->_load_words($self->{'unknown_lex'});
873 0 store \%_LEXICON, $self->{'word_path'};
874 0 store \%_HMM, $self->{'tag_path'};
875 }
876  
877  
878 ########################################################
879 # LOAD THE 2-GRAMS INTO A HASH FROM YAML DATA
880 #
881 # This is a naive (but fast) YAML data parser. It will
882 # load a YAML document with a collection of key: value
883 # entries ({pos tag}: {probability}) mapped onto
884 # single keys ({tag}). Each map is expected to be on a
885 # single line; i.e., det: { jj: 0.2, nn: 0.5, vb: 0.0002 }
886 #########################################################
887 1 ▶sub _load_tags {
Subroutine _load_tags: called CC=5 SCAR=16.1
888 1 my ($self, $lexicon) = @_;
889  
890 1 my $path = File::Spec->catfile($lexpath, $lexicon);
891 1 ▶ my $fh = new FileHandle $path or die "Could not open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "FileHandle"->new($path) or die "Could not open ${path}: $!" 1 0 1
892 1 ▶ while(<$fh>){
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 45 1 46
893 45 ▶ next unless my ($key, $data) = m/^"?([^\{"]+)"?: \{ (.*) \}/;
Branch: 1 branch
BranchTrueFalseTotal
unless () = /^"?([^\{"]+)"?: \{ (.*) \}/ 1 44 45
894 44 my %tags = split /[:,]\s+/, $data;
895 44 foreach(keys %tags){
896 1397 $_HMM{$key}{$_} = $tags{$_};
897 }
898 }
899 1 $fh->close;
900 }
901  
902  
903 #########################################################
904 # LOAD THE WORD LEXICON INTO A HASH FROM YAML DATA
905 #
906 # This is a naive (but fast) YAML data parser. It will
907 # load a YAML document with a collection of key: value
908 # entries ({pos tag}: {count}) mapped onto single
909 # keys ({word}). Each map is expected to be on a
910 # single line; i.e., key: { jj: 103, nn: 34, vb: 1 }
911 #########################################################
912 2 ▶sub _load_words {
Subroutine _load_words: called CC=5 SCAR=16.1
913 2 my ($self, $lexicon) = @_;
914  
915 2 my $path = File::Spec->catfile($lexpath, $lexicon);
916  
917 2 ▶ my $fh = new FileHandle $path or die "Could not open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "FileHandle"->new($path) or die "Could not open ${path}: $!" 2 0 2
918 2 ▶ while(<$fh>){
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 43830 2 43832
919 43830 ▶ next unless my ($key, $data) = m/^"?([^\{"]+)"?: \{ (.*) \}/;
Branch: 1 branch
BranchTrueFalseTotal
unless () = /^"?([^\{"]+)"?: \{ (.*) \}/ 2 43828 43830
920 43828 my %tags = split /[:,]\s+/, $data;
921 43828 foreach(keys %tags){
922 51989 $_LEXICON{$key}{$_} = \$tags{$_};
923 }
924 }
925 2 $fh->close;
926 }
927  
928  
929 ############################
930 # RETURN TRUE
931 ############################
932 10 1;
933  
934  
935 __END__
↑ Summary