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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dipak Singh
    New Member
    • Feb 2011
    • 8

    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:
    Code:
    #printing the file
    open (MYFILE, 'C:\Documents and Settings\dsingh20\My Documents\Perl_Task.txt');
     
    
    while (<MYFILE>)
    
     {
    	chomp;
     	print "$_\n";
     }
    #taking input from user and printing the same
    print "Enter The Words You want to Search - " ; # printing on the STDOUT
    
    $line = <STDIN>;#read line
    
    $line =~ s/(^\s+)|(\s+$)//g;#remove lead and trail white space
    
    @data = split(/\s+/,$line);#split on white space into array
    
    print " Words entered by the user are: \n\n";
    
    
    foreach $data (@data) 
    
    {
            print" $data \n" ;
    
    }
    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:
    Code:
    foreach $data (@data)
    {
    my $count = 0;
    while (/$data/ig, <MYFILE>)
    {
    $count++;
    }
    print "$count occurance found:;
    }
    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
    Last edited by numberwhun; Feb 22 '11, 01:54 PM. Reason: Please use code tags!
  • NetDynamic
    New Member
    • Feb 2011
    • 27

    #2
    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.

    Comment

    • miller
      Recognized Expert Top Contributor
      • Oct 2006
      • 1086

      #3
      Code:
      use strict;
      
      # Get Words
      my $line = <STDIN>;
      my @words = $line =~ m/(\w+)/g;
      print "Words entered by the user are: @words\n\n";
      
      # Build Regex
      my $words_re = do {
      	my $words = join '|', @words;
      	qr{$words};
      };
      
      my %count;
      
      # Process File
      my $file = 'C:\Documents and Settings\dsingh20\My Documents\Perl_Task.txt';
      open my $fh, $file or die "Can't open file, $file: $!";
      while (<$fh>) {
      	$count{$_}++ foreach /($words_re)/g;
      }
      close $fh;
      
      # Print Results;
      while (my ($word, $count) = each %count) {
      	print "$word = $count\n";
      }
      
      1;
      
      __END__

      Comment

      • Dipak Singh
        New Member
        • Feb 2011
        • 8

        #4
        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

        Comment

        • rovf
          New Member
          • May 2010
          • 41

          #5
          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).

          Comment

          • miller
            Recognized Expert Top Contributor
            • Oct 2006
            • 1086

            #6
            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

            Comment

            • Dipak Singh
              New Member
              • Feb 2011
              • 8

              #7
              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

              Comment

              • Dipak Singh
                New Member
                • Feb 2011
                • 8

                #8
                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

                Comment

                • miller
                  Recognized Expert Top Contributor
                  • Oct 2006
                  • 1086

                  #9
                  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

                  Comment

                  • Dipak Singh
                    New Member
                    • Feb 2011
                    • 8

                    #10
                    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\dsingh 20\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;

                    Comment

                    • miller
                      Recognized Expert Top Contributor
                      • Oct 2006
                      • 1086

                      #11
                      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.

                      Comment

                      • Dipak Singh
                        New Member
                        • Feb 2011
                        • 8

                        #12
                        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.

                        Comment

                        • miller
                          Recognized Expert Top Contributor
                          • Oct 2006
                          • 1086

                          #13
                          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

                          Comment

                          • Dipak Singh
                            New Member
                            • Feb 2011
                            • 8

                            #14
                            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

                            Comment

                            • rovf
                              New Member
                              • May 2010
                              • 41

                              #15
                              > 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

                              Comment

                              Working...