【问题标题】:How to determine number of times a word appears in text?如何确定一个单词在文本中出现的次数?
【发布时间】:2011-07-16 02:30:59
【问题描述】:

如何在 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";
  }
}  

我想找到该文本文件的“计数”字数。文件名为可怕的.pl

理想情况下,它应该使用 regex最少 行代码。

编辑:这是我尝试过的:

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};

【问题讨论】:

  • 请尽力而为,如果您仍有疑问或问题,请回到这里。这不是一个“我们会为你做功课”的网站。

标签: regex perl file text


【解决方案1】:

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

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

【讨论】:

  • /g 列表上下文中模式匹配中的选项。脱帽致敬!
  • 它在 .pl 文件中并不那么晦涩难懂,但这或多或少是等价的:$/=0777;@ARGV=qw(terrible.pl);print+(@@=/count/g)+0while&lt;&gt; 注意:我正在为另一个项目保存空白。
  • @LHMathies 我有一个这样的问题:stackoverflow.com/questions/5402405/… 你能检查一下吗,是否可以从命令行重写它?一个答案是: perl -e 'open A,";打开 B,";y/GCTA/CGAU/;map{print if$_=$p{$_}}/(...)/g ' 但是我认为它可能会更少。
【解决方案2】:

如果您要计算单词“count”出现的次数,这将起作用:

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

【讨论】:

    【解决方案3】:

    我实际上并不确定您的示例代码是什么,但您快到了:

    perl -e '$text = "lol wut foo wut bar wut"; $计数 = 0; $count++ 而 $text =~ /wut/g;打印 "$count\n";'

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

    【讨论】:

      【解决方案4】:

      你可能会使用这样的东西:

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

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

      【讨论】:

      • 我只需要给定单词的获取时间。我的话找到count的数量是:“count”。
      【解决方案5】:

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

      鉴于这似乎是一个家庭作业问题,我将向您指出文档。

      【讨论】:

        【解决方案6】:

        那么,你想做什么?您需要某物在文本块中出现的次数。您可以使用 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
        }
        

        【讨论】:

          猜你喜欢
          • 2013-10-10
          • 2017-08-14
          • 1970-01-01
          • 1970-01-01
          • 2012-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多