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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.