2011-01-31 54 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; 
相關問題