Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
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 ( #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.

  • Comment on Re: How do I count the frequency of words in a file and save them for later?
  • Download Code

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? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2023-02-02 10:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (17 votes). Check out past polls.

    Notices?