如何计算文本中的STDIN中输入的特定单词(PERL)

时间:2017-09-29 08:54:16

标签: perl

如何统计文本中的STDIN中输入的特定单词(PERL) 我的输出只计算文本中发现的所有owrds。但我需要在STDIN中输入的具体单词

open my($file), '<','C:\Users\yukari\Desktop\hi.txt' or die "not exist";

print "Search the word:";
$word = <STDIN>;

print "\n";

while ( my $line = <$file> ) {
    chomp($line);

    # print $line; 

    foreach $word (split(' ', $line)) {
        $count{$word}++;
    }
}

foreach $word (sort keys %count) {
    print "$word: $count{$word}\n";
}

2 个答案:

答案 0 :(得分:0)

我相信你想从用户那里得到一个单词并计算整个文本文件中该单词的出现次数。

您可以尝试这样的事情:

use strict;
use warnings;

open(WRITE,'>','log.txt') or die "Unable to open the file";
my $string = <<END;
foo baz bar
baz bar bar foo
foo foo bar bar baz baz
baz baz baz
END

print WRITE $string;
close WRITE;

open(READ, '<','log.txt') or die "unable to open the file";

my $search = <STDIN>;
chomp $search;
my $count = 0;

while ( my $line = <READ> ) {
    chomp($line);
    my @words = split(' ',$line);
    foreach my $word(@words){
        $count++ if($word eq $search);
    }
}
close READ;
print "Search string: $search, Count: $count","\n"; 

答案 1 :(得分:0)

你这里有问题。您正在使用变量$word进行三种不同的操作。

您正在使用它作为您要搜索的单词:

$word = <STDIN>;

您正在使用它将每个单词存储在从您的文件中读取的行上:

foreach $word (split(' ', $line)) {

您正在使用它来包含您最后从哈希中读取的键。

foreach $word (sort keys %count) {

特别是,第二种用途是干扰第一次使用。当您从文件中读取数据时,您无法知道要查找的单词。

如果您要查找单个单词,则无需使用哈希来存储计数。我这样编写你的代码:

# ALWAYS INCLUDE THESE
use strict;
use warnings;

use feature 'say';

# Renamed your variable, it's a file handle, not a file.
# Also, include $! in error message so we know what really
# went wrong.
open my $fh, '<', 'C:\Users\yukari\Desktop\hi.txt'
    or die "Can't open file: $!";

print "Search the word:";
my $search_word = <STDIN>;

print "\n";

# Scalar variable to store the count
my $count;

# Remove the $line variable and use Perl's default variable $_
# instead. This makes the code *far* cleaner.
while ( <$file> ) {
    chomp;

    # By default, split splits $_ on whitespace
    foreach $word (split) {
        # Skip words we don't care about
        next if $word ne $search_word;
        # Increment the counter
        $count++;
    }
}

say "$search_word appeared $word times";