Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

perl - reading file line by line

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...