【问题标题】:Counting Sentences/Words in Perl Using Regex使用正则表达式计算 Perl 中的句子/单词
【发布时间】:2011-01-31 01:02:41
【问题描述】:

这个正则表达式已经过时了。 :( 还有一个问题: 我需要计算段落中的单词数和句子数。我尝试使用的代码是这样的:

my $sentencecount = $file =~ s/((^|\s)\S).*?(\.|\?|\!)/$1/g;
my $count = $file =~ s/((^|\s)\S)/$2/g;
print "Input file $ARGV[1] contains $sentencecount sentences and $count words.";

我的结果对这两个计数都返回 63。我知道这是不正确的,至少就字数而言。这是使用替代计数过程的结果吗?如果是这样,我该如何纠正?

【问题讨论】:

  • 你知道,我认为可能有更简单的方法来计算字符串中的单词...
  • 显然你应该发布输入文件。
  • 另外,s///g 替换文本开始每个匹配项(这样,s/a/ab/g 就不会导致无限循环)。这就是问题的一部分。此外,您的句子计数正则表达式非常奇怪——它用该句子中的第一个字符替换了第一句话(可能前面有一个空格)——这就是 $1 中的内容。
  • 但是C.S. Lewisabr.

标签: regex perl count word


【解决方案1】:

我建议查看 perl split 函数,请参阅 perlfunc(1)

           If EXPR is omitted, splits the $_ string.  If PATTERN is also
           omitted, splits on whitespace (after skipping any leading
           whitespace).  Anything matching PATTERN is taken to be a
           delimiter separating the fields.  (Note that the delimiter may
           be longer than one character.)

【讨论】:

  • 其实我在研究拆分功能,但是我所在的网站真的很糟糕,我当时没有意识到,所以我跳过了它,但是,是的,谢谢你,我得到了这个愚蠢的代码工作。谢谢!
【解决方案2】:
my $wordCount = 0;
++$wordCount while $file =~ /\S+/g;

my $sentenceCount = 0;
++$sentenceCount while $file =~ /[.!?]+/g;

在标量上下文中进行//g 匹配可以避免构建包含所有单词或所有句子的庞大列表,如果文件很大,可以节省内存。句子计数代码会将任意数量的句尾分隔符计为一个句子(例如,Hello... world! 将计为 2 个句子。)

【讨论】:

    【解决方案3】:

    这会从$file获取句子和字符的计数

    $file="This is praveen worki67ng in RL websolutions";
    my $count = () = $file =~ /\S+/g;
    my $counter = () = $file =~ /\S/g;
    

    【讨论】:

    • 这是从 $file 中获取句子和字符的计数
    猜你喜欢
    • 2015-09-01
    • 2013-11-08
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 2018-07-17
    • 2014-01-03
    相关资源
    最近更新 更多