473,379 Members | 1,330 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

How to count no. of occurance with line no. of multiple words individually in a file?

Hi,

I am a beginner at perl. I am writing a program to open a file, take input from user for the words he wants to search within that file, print it then print the no of occurance of each word with respective line no.s in the file.


Below is the code written by me:
Expand|Select|Wrap|Line Numbers
  1. #printing the file
  2. open (MYFILE, 'C:\Documents and Settings\dsingh20\My Documents\Perl_Task.txt');
  3.  
  4.  
  5. while (<MYFILE>)
  6.  
  7.  {
  8.     chomp;
  9.      print "$_\n";
  10.  }
  11. #taking input from user and printing the same
  12. print "Enter The Words You want to Search - " ; # printing on the STDOUT
  13.  
  14. $line = <STDIN>;#read line
  15.  
  16. $line =~ s/(^\s+)|(\s+$)//g;#remove lead and trail white space
  17.  
  18. @data = split(/\s+/,$line);#split on white space into array
  19.  
  20. print " Words entered by the user are: \n\n";
  21.  
  22.  
  23. foreach $data (@data) 
  24.  
  25. {
  26.         print" $data \n" ;
  27.  
  28. }
  29.  
Upto this the program is doing fine but I am not able to count the no of occurance of each word given as input by user though I tried the following:
Expand|Select|Wrap|Line Numbers
  1. foreach $data (@data)
  2. {
  3. my $count = 0;
  4. while (/$data/ig, <MYFILE>)
  5. {
  6. $count++;
  7. }
  8. print "$count occurance found:;
  9. }
  10.  
And I am not able to get the line no.'s for each word also.


Please help. Thanks in advance for any help.


Regards,
Dipak Kumar Singh
Feb 22 '11 #1
14 4221
Well since i haven't bothered with the now almost completely obsolete PERL in so long i don't recall the best way but a crappy way would be to break each line into an array of words and pop off each match in sub-loops I guess. It would also make it easy to make an array of line numbers.
Feb 22 '11 #2
miller
1,089 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. use strict;
  2.  
  3. # Get Words
  4. my $line = <STDIN>;
  5. my @words = $line =~ m/(\w+)/g;
  6. print "Words entered by the user are: @words\n\n";
  7.  
  8. # Build Regex
  9. my $words_re = do {
  10.     my $words = join '|', @words;
  11.     qr{$words};
  12. };
  13.  
  14. my %count;
  15.  
  16. # Process File
  17. my $file = 'C:\Documents and Settings\dsingh20\My Documents\Perl_Task.txt';
  18. open my $fh, $file or die "Can't open file, $file: $!";
  19. while (<$fh>) {
  20.     $count{$_}++ foreach /($words_re)/g;
  21. }
  22. close $fh;
  23.  
  24. # Print Results;
  25. while (my ($word, $count) = each %count) {
  26.     print "$word = $count\n";
  27. }
  28.  
  29. 1;
  30.  
  31. __END__
Feb 22 '11 #3
Hi,


Thanks for your reply. But it is only taking the input and printing them sequentially:(. Nothing else is happening... Please help


Regards,
Dipak Kumar Singh
Feb 22 '11 #4
rovf
41
Could you please be more precise about where your problem is? You don't even post code (except your initial version which you, presumably, have modified in the meantime).
Feb 22 '11 #5
miller
1,089 Expert 1GB
Dipak,

I gave you a solution, it's up to you to read at http://perldoc.perl.org/ what all it is doing.

If you have a specific problem, please post your code and state explicitly what error messages your getting or where you think the problem might be. Otherwise, we really can't help you anymore.

- Miller
Feb 22 '11 #6
Hi Miller,

I am not able to go into the loop for conuting the no. of occurance of each input word taken from the user. The code submitted by me is still the same. I tried to run your code it's showing syntax errors! Sometimes it's giving "unmatched curly braces" and sometimes it's not even taking inputs.. Please run your code once to get the same.


Regards,
Dipak Kumar Singh
Feb 23 '11 #7
Hi rowf,

I am not able to go into the loop for conuting the no. of occurance of each input word taken from the user. The code submitted by me is still the same.


Regards,
Dipak Kumar Singh
Feb 23 '11 #8
miller
1,089 Expert 1GB
Dipak,

The code I submitted to you does not contain any syntax errors. I name it compare.pl, and then rename the file that it's matching compare.pl as well.

It works exactly as designed.

- M
Feb 23 '11 #9
Hi Miller,

Yeah it worked now! It was not able to locate "strict.pm". Also only those words were getting count and printed which matched in the file.
I worked on the code to get a desired output for word count. But still I am not able to assign the respective line no.s for each word where they are matched. Please help. Refer to the code below for any suggestion:


my @file;
my $i=0;
my $cntr = 0;
# Get Words
print "Enter the location with file name which you want to search: \n";
my $file = <STDIN>;
print "Enter the words you want to search: \n";
my $line = <STDIN>;
my @words = $line =~ m/(\w+)/g;
print "Words entered by the user are: @words \n\n";

undef $/;

#Process File
#my $file = 'C:\Documents and Settings\dsingh20\My Documents\Perl_Task.txt';
open FILE, $file or die "Can't open file, $file: $!";
my $temp = <FILE>; #the file is passed on to a string since $/ is set to undef

#the string is then split into individual words without whitespace, punctuation marks etc
my @file = $temp =~ m/(\w+)/g;

#word matching
foreach $words (@words){
foreach $file (@file){
if ($file eq $words){
$cntr++;
}
}
print "$words: $cntr\n\n";
$cntr = 0;
}
close FILE;
Feb 23 '11 #10
miller
1,089 Expert 1GB
What exactly are you trying to accomplish? This description is unclear

I worked on the code to get a desired output for word count. But still I am not able to assign the respective line no.s for each word where they are matched. Please help.
Feb 23 '11 #11
What I want is as below:

My FIle is like this:

Reading from a file in perl Perl gives us a way to create "flat text file" databases. These can be useful, and are fairly easy to Try set up. The downside is that you need to deal with file permissions, and there is the possibility of data being overwritten. is Is However, as we get into it further we will try to discuss those issues in more detail. First, let's take a look at how to get started.


Now I want my code to do the following:

#Enter the file to be searched: User inputs file name with location
#Enter words to be searched: Say user inputs 'Perl perl Try try'


I need the program to show the following output:
Word No. of occurance Line no.s
Perl say 'n' or '0' say 'a' 'b' 'c'....
perl say 'n' or '0' say 'a' 'b' 'c'....
Try say 'n' or '0' say 'a' 'b' 'c'....
try say 'n' or '0' say 'a' 'b' 'c'....



I hope it clears your doubt. Please check.


Regards,
Dipak Kumar Singh.
Feb 24 '11 #12
miller
1,089 Expert 1GB
Dipak,

If you're having trouble with this project, I suggest that you ask your professor or teaching assistant first. If you have a specific perl related question or bug in your code that you need help locating, we can help with that.

But it's actually against the forum rules to do someone's homework for them.

- Miller
Feb 24 '11 #13
Miller,

Sorry to say that I was trying to do this program on my own. I was having a joint learning session of Perl with one of my friends. It was not any kind of homewprk. BTW many thanks for your all replies. Hope to see help from you later in some other topic.


Regards,
Dipak Kumar Singh
Feb 25 '11 #14
rovf
41
> It was not able to locate "strict.pm".

This is a standard module since Perl 5. Either you are using Perl 4 (please check with "perl --version"), or your installation is seriously broken (in which case I only can suggest re-installing Perl - I wouldn't trust a Perl installation which not even has strict.pm!).

Ronald
Feb 26 '11 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Christopher R. Barry | last post by:
I need to search and replace multiple words in one pass of an input stream or string. For example, given the input: "The quick brown fox jumped over the lazy dog's back" and given the...
9
by: Jonny | last post by:
Hi, Please could you tell me what the quickest way would be to verify that a line of text exists in a file. I would like to be able to do something like: grep "^line of text$" filename.txt...
2
by: Clodoaldo Pinto Neto | last post by:
Hi all, I'm trying to copy a table with a text field column containing a new line char to a file: ksDesenv=# create table page(line text) without oids; CREATE TABLE ksDesenv=# insert into...
2
by: Eric Lilja | last post by:
Hello, I'm writing a simple program that upon start-up needs to open a text file and read a value on the last line. Then all other accesses to the file will be writes (at the end of it). I'm having...
5
by: vonclausowitz | last post by:
Repost from an VB group. Hi All, I'm looking for a way to search for multiple words in a database. There is however one but. The words have to be within a certain range of each other. For...
4
by: writeanand | last post by:
How can I count the frequency of words in a ASCII File using STL? I dont know what words will be found in the file ahead of time. I dont want to use any classes, just a simple program wd do. ...
2
by: surekhareddy | last post by:
can i count the number of words in a file
2
by: Govind Pandey | last post by:
Hi, I am trying to replace multiple words from the text box. for example: I want few words should be in Upper case only. Like "cat" to be replaced with "CAT", "dog" always appears as "DOG",...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.