Dear Monks
I would like to extract from an abstract, all unique phrases of two-, three- and four-words length in seperate groups. Order of the words in the phrase must be preserved but the order of the phrases in the output need not be. Using a hash achieves this in addition to removing duplicates if any. Please see below for my solution that achieves what i want.
However, I would like to know what is a better way as this approach will be cumbersome to scale up for phrases of n-words length as n gets larger.
Thanks in advance.
#!/usr/bin/perl
use strict;
use warnings;
my $abstract = 'Perl is a high-level, general-purpose, interpreted, dy
+namic programming language.';
my (%double_words, %triple_words, %four_words);
my @words = split(/\s+/, $abstract);
foreach(0..$#words){
$double_words{$words[$_].' '.$words[$_+1]}= undef if($_<$#words);
$triple_words{$words[$_].' '.$words[$_+1].' '.$words[$_+2]}= undef
+if($_<$#words-1);
$four_words{$words[$_].' '.$words[$_+1].' '.$words[$_+2].' '.$words
+[$_+3]}= undef if($_<$#words-2);
}
foreach(keys %four_words){ print $_."\n"; } #sample output
Sample output of all four-word phrases:
general-purpose, interpreted, dynamic programming
a high-level, general-purpose, interpreted,
Perl is a high-level,
interpreted, dynamic programming language.
is a high-level, general-purpose,
high-level, general-purpose, interpreted, dynamic
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.