Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two files which I want to read line by line (the first contains a word per line and the second a sentence per line).

The goal is to calculate the number of the sentences from file 2 containing a word being in file 1.

Here is my code:

open( my $words, '<:utf8', 'test' ) or die "Unable to open for read: $!"; `#test file is the file that contain my words`
open( my $sentences, '<:utf8', 'sentences' ) or die "Unable to open for read: $!"; `#sentences fila that contain one sentence per line`
open my $fh_resultat, ">:utf8", 'result';
my $word;
#i want to calculate the number of sentences from my $sentences that containe word from my file $words
while( defined( $word = <$words> ) ) {
    chomp $word ;
    $word =~ s/^s*|s*$//g;
    my $nb = 0;
    my $idf;
    my $ph;
    while (defined ( $ph = <$sentences> ) ){
        my @tab = split(/ /, $ph);
        chomp @tab ;
        foreach my $val(@tab) {
            if($word eq $val){
                $nb = $nb + 1;
                last;
            }
        }
    }
    print $fh_resultat "$word:$nb
";
}

but the processing is only performed for the first word of the first file!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you read a filehandle to the end of the file, the next read from that filehandle will return undef. And it will continue to return undef no matter how many times you call it.

You cannot iterate through the phrase file without using the seek() function to reset the file pointer to the start of the file.

seek $CorpusPhrases, 0, 0;

Alternatively, you might consider reading one (or both) of your files into memory so you don't need to keep reading the files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...