blib/lib/Lingua/DE/Tagger.pm untested

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