Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Wise monks

I am trying to put a script together that will go through a text file and show me the top 5 words sorted my occurrence. Here is where I am at:

while (<>) { chop; my @words = split; foreach $wd (@words) { next if length($wd) < 5; $count{$wd}++; } } foreach $w (keys %count) { print "$count{$w} $w\n"; }

As you can see, I am only interested in words over 5 characters in length. I am unsure how to go about sorting this by number of occurrence. Also, I am having problems with punctuation showing up in my results. I have an example below:

2 usurpations, 2 purpose 1 people. 1 obstructed 1 formidable 1 obstructing 1 uncomfortable,

Is this because I am using split? Is there a better way to go about this. I am sure I will start missing words that have apostrophes too. Also, how should I sort this? Then how can I take only the top 5?

Any help or advice is appreciated.

Many thanks,

In reply to Top five words by occurrence by ghettofinger

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others studying the Monastery: (9)
    As of 2020-02-28 19:09 GMT
    Find Nodes?
      Voting Booth?
      What numbers are you going to focus on primarily in 2020?

      Results (127 votes). Check out past polls.