count words - Programmers Heaven

Howdy, Stranger!

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

Categories

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.