如何确定单词在文本中出现的次数?

时间:2011-03-15 20:13:31

标签: regex perl file text

如何在Perl中找到单词在文本块中的次数?

例如我的文本文件是:

#! /usr/bin/perl -w
# The 'terrible' program - a poorly formatted 'oddeven'.
use constant HOWMANY => 4; $count = 0;
while ( $count < HOWMANY ) {
  $count++;
  if ( $count == 1 ) {
    print "odd\n"; 
  } elsif ( $count == 2 ) { 
    print "even\n";
  } elsif ( $count == 3 ) {
    print "odd\n";
  } else { # at this point $count is four.
    print "even\n";
  }
}  

我想找到&#34; count&#34;该文本文件的单词。文件名为terrible.pl

理想情况下,它应该使用正则表达式并使用最小代码行数。

编辑:这就是我的尝试:

use IO::File;
my $fh = IO::File->new('terrible.pl', 'r') or die "$!\n";
my %words;
while (<$fh>) {
  for my $word ($text =~ /count/g) {
  print "x";
    $words{$word}++;
  }
}
print $words{$word};

6 个答案:

答案 0 :(得分:6)

这是一个完整的解决方案。如果这是家庭作业,你可以通过向老师解释这一点来学习更多内容,而不是自己动手:

perl -0777ne "print+(@@=/count/g)+0" terrible.pl

答案 1 :(得分:1)

如果您正在尝试计算单词“count”的次数,则可以使用:

my $count=0;
open(INPUT,"<terrible.pl");
while (<INPUT>) {
    $count++ while ($_ =~ /count/g);
}
close(INPUT);
print "$count times\n";

答案 2 :(得分:0)

我真的不确定你的示例代码是什么,但你几乎就在那里:

perl -e'$ text =“lol wut foo wut bar wut”; $ count = 0; $ count ++而$ text =〜/ wut / g;打印“$ count \ n”;'

您可以使用/ g修饰符继续在字符串中搜索匹配项。在上面的示例中,它将返回$ text var中单词'wut'的所有实例。

答案 3 :(得分:0)

您可以使用类似的东西:

my $fh = IO::File->new('test.txt', 'r') or die "$!\n";
my %words;
while (<$fh>) {
  for my $word (split / /) {
    $words{$word}++;
  }
}

这将为您准确计算每个“单词”(定义为由空格分隔的一组字符),并将其存储在一个散列中,该散列由单词键入,其值为单词的数字值被人看见了。

答案 4 :(得分:0)

perdoc perlrequick有一个答案。您在该文档中需要的术语是“标量上下文”。

鉴于这似乎是一个家庭作业问题,我会指出你的文档。

答案 5 :(得分:0)

那么,你想做什么?您想要在文本块中出现某些内容的次数。您可以使用Perl grep功能。这将通过一个文本块而无需循环。

如果需要奇数/偶数返回值,可以使用modulo算术函数。你可以这样做:

if ($number % 2) {
   print "$number is odd\n"; #Returns a "1" or true
}
else {
   print "$number is even\n";  #Returns a "0" or false
}