如何确定单词在文本中出现的次数? [英] How to determine number of times a word appears in text?

查看:71
本文介绍了如何确定单词在文本中出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中如何查找单词在文本块中的出现次数?

How can I find the number of times a word is in a block of text in Perl?

例如,我的文本文件是这样的:

For example my text file is this:

#! /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";
  }
}  

我想找到该文本文件的计数"字数.文件名为terrible.pl

I want to find the number of "count" word for that text file. File is named terrible.pl

理想情况下,它应使用 regex ,并使用最小行代码.

Idealy it should use regex and with minimum number of line of code.

编辑:这是我尝试过的操作:

This is what I have tried:

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

推荐答案

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

Here's a complete solution. If this is homework, you learn more by explaining this to your teacher than by rolling your own:

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

这篇关于如何确定单词在文本中出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆