Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: How do I count the frequency of words in a file and save them for later?

by amitbhosale (Acolyte)
on Feb 13, 2008 at 08:09 UTC ( [id://667742]=note: print w/replies, xml ) Need Help??


in reply to How do I count the frequency of words in a file and save them for later?

this script counts the occurrence of each word present in the file and print a summary.
#!/usr/bin/perl -w use strict; use IO::File; my %seen=(); my $file_name="/home/myprog/matter"; my $file=IO::File->new("< $file_name") or die "Couldn't open $file_nam +e for reading:$! \n"; my $line; while(defined($line=$file->getline())) { foreach my $word (split / /,$line) { chomp($word); if ($word =~ /\w+/) { $word =~ s/[. ,]$//; if ($seen{$word}) { my $count; $count=$seen{$word}; $count=$count+1; $seen{$word}=$count; } else { $seen{$word}=1; } }# if ($word =~ /\w+/) end here } # foreach my $word (split / /,$line) end here } # while(defined($line=$file->getline())) print "\n =============== o/p Word and it's count frequency=========== +============="; foreach my $val (keys %seen) { print "\n $val => $seen{$val}"; } $file->close();
Let me know if any changes are required.

Originally posted as a Categorized Answer.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://667742]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (9)
As of 2024-03-28 09:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found