Perl

Moderators: Jonathan
Number of threads: 1236
Number of posts: 3605

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
count words Posted by txantxan on 29 Nov 2004 at 1:53 PM
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
Report
Re: count words Posted by Jonathan on 29 Nov 2004 at 3:38 PM
: 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.

#!/usr/bin/perl

# Hash.
my %wordcount;

# Go through each line in the file.
open FILE, "< thefile.txt";
while (my $line = <FILE>) {
    # 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{$_}\n" for sort keys %wordcount;


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.");




 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.