2011-01-31 55 views
2

这个正则表达式事情正在变老。 :( 另一个问题: 我需要计算一个段落句子中的单词数和号码,我尝试使用的代码是这样的:使用正则表达式计算Perl中的句子/单词

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我知道这如果是这样,我该如何纠正这个问题?

+0

你知道,我认为可能有更简单的方法来计算字符串中的单词...... – 2011-01-31 01:06:28

+0

显然你应该发布输入文件。 – 2011-01-31 01:24:58

+0

另外``/// g``在替换文本之后从*开始每个匹配(因此,例如`s/a/ab/g`不会导致无限循环)。这是问题的一部分。此外,您的句子计数正则表达式非常奇怪 - 它将第一个句子替换为该句子中的第一个字符(可能前面有一个空格) - 这就是$ 1中的内容。 – 2011-01-31 01:45:26

回答

2

我建议看看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.) 
1
my $wordCount = 0; 
++$wordCount while $file =~ /\S+/g; 

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

//g匹配标量上下文,因为我们这里避免了建立一个巨大的所有单词或所有句子的列表,如果文件很大,节省内存。句子计数代码将计数任意数量的结束句子定界符作为一个简单的句子(例如Hello... world!将被算作2句。)

0

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

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