I mentioned in Re: Most common substring that I had a snippet to scan a text and report the most common substrings. This is useful in language analysis problems as well as some forms of encryption and compression.

This snippet scans an input and counts occurrences of substrings. For the input sentence:

off the record, heretofore, the officer found that in the theater of war, one hath need of a weatherproof theory of games

The output would begin:

8<th> 7<of> 7<he> 6<the> 6< th> 6< t> 5< o> 5<f > 5< the> 4<at> 4<of > 4<e > 4<er> 4< of>

The report format is similar to files included in the Moby Lexicon Project.

#!/usr/bin/perl # Write a substring analysis of an input text, like Moby's sample. # All whitespace is considered a single space. use strict; use Getopt::Long; my %Substrings; my $Minimum = 2; my $Shortest = 2; my $Longest = 5; my $Limit = 500; GetOptions('minimum=i' => \$Minimum, 'shortest=i' => \$Shortest, 'longest=i' => \$Longest, 'limit=i' => \$Limit); exit(main(@ARGV)); sub main { my $input; do { local $/ = undef; $input = <>; }; $input =~ s/\n/ /gs; $input =~ s/\s+/ /gs; for my $span ($Shortest .. $Longest) { for my $pos (0 .. length($input)-$span) { $Substrings{ substr($input, $pos, $span) }++; } } my $count = 0; foreach (grep { not $Limit or $count++ < $Limit } grep { $Substrings{$_} >= $Minimum } sort { $Substrings{$b} <=> $Substrings{$a} } keys %Substrings) { print $Substrings{$_}, '<', $_, '>', "\n"; } }

In reply to count moby substrings by halley

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.