Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

count words

txantxantxantxan Posts: 2Member
I want to count words from a file. For example how many times appears the word "example" in a file. I thougth to use grep, but grep only counts the lines (if in the same line appears more than one "example" doesn't count as 2).
Is there a simple way to do that?
I don't mind if it is in another language (not in Perl).
Thanks

Comments

  • JonathanJonathan Posts: 2,914Member
    : I want to count words from a file. For example how many times appears the word "example" in a file. I thougth to use grep, but grep only counts the lines (if in the same line appears more than one "example" doesn't count as 2).
    : Is there a simple way to do that?
    : I don't mind if it is in another language (not in Perl).
    : Thanks
    :
    Use a hash: use the word as the hash key and increment the value in the hash every time we see the word. The print the list out at the end.

    [code]#!/usr/bin/perl

    # Hash.
    my %wordcount;

    # Go through each line in the file.
    open FILE, "< thefile.txt";
    while (my $line = ) {
    # Remove non-word characters.
    $line =~ s/[^w']//g;

    # Split and increment hash count for each word.
    $wordcount{$_}++ for split(/s+/, $line);
    }
    close FILE;

    # Print word count list.
    print "$_: $wordcount{$_}
    " for sort keys %wordcount;[/code]

    Getting the count for an individual words is easy too. :-)

    Have fun,

    Jonathan

    ###
    for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&&
    (tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
    /(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");

Sign In or Register to comment.