May 10, 2010
Word count perl script
Find word count using perl
Write a perl program that prints word count in file. For example if the input file contains the following word occurrences “Santa Clara is located in Santa Clara county” the program should print something like:
Santa: 2
Clara: 2
is: 1
located: 1
in: 1
county: 1
Word count perl hash
Read the file line by line then split by word then update the count of the current read word using some hashing technique.
Count word frequency perl code
Here is a suggested solutin in Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#!/usr/bin/perl # This is a hash table. you give me the word I give you the count. # for example $word_count_hash{"myword"} would give you 10 %word_wount_hash = (); # File name $file_name = "word_count.txt"; # Open the file for reading open (FH, $file_name) or die "could not open file"; # Read the file line by line while ($line = ) { # Remove end of line character chomp($line); # Split the current line into words using the space character # as a separator and save them into an array @line_words = split (" ", $line); # Loop through the words in the current lines foreach $word (@line_words) { # Increment the count for that word $word_count_hash{$word}++; } } close(FH); # Print the hash content foreach $word (keys %word_count_hash) { print $word . " : " . $word_count_hash{$word} . "\n"; } |
If you have a question or comments, please use the comments section below. Thanks for visiting.