Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

Counting diagraphs and trigraphs in Perl

Posted on 2004-08-21
Medium Priority
484 Views
Hi,
I have a string in perl say    "hh bbb. rt irr"

I'm looking for some way of going through that string and counting how many three letter words there are and how many two letter words. punctuation should be ignored....

Any takers? :)

0
Question by:petepalmer
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 10

Expert Comment

ID: 11859203
\$text="hh bbb. rt irr";
@words = split(/[\s.,;:\'\"\\\/\`\~\!\@\#\\$\%\^\& \*\(\)\_\- \+\+\[\]\{\}\?]+/,\$text);
foreach(@words) {
\$twocharwords++ if length(\$_)==2;
\$threecharwords++ if length(\$_)==3;
}
print "two char word count: \$twocharwords, three char word count: \$threecharwords\n";
0

LVL 20

Accepted Solution

jmcg earned 1000 total points
ID: 11859824
(spelling error in title corrected)

Actually, the words digraph and trigraph are usually used with a different meaning: they refer to two-character and three-character sequences regardless of whether they appear as independent words or as part of larger words. The statistics of digraphs and trigraphs can be used in compression algorithms and in code breaking.

If we take from your question that you want to count the number of two- and three-character sequences (sequences, that is, containing alphabetic characters only), the approach that rj2 has shown is pretty good. If I were doing it, I'd probably do it more like:

my @words = \$text =~ m{\b([a-zA-Z]+)\b}g;
my @histogram;
\$histogram[length]++ foreach @words;
print "length\tcount\n";
printf "%5d\t%5d\n" \$_, \$histogram[\$_] foreach (2..3);

or, change that last line to get the entire histogram,

printf "%5d\t%5d\n" \$_, \$histogram[\$_] foreach (1 .. \$#histogram);

0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses
Course of the Month5 days, 8 hours left to enroll