2017-02-14 76 views
2

我已經到了可以用句子標點符號的簡單句尾來分割和計算句子的點! ? 。使用Ruby計算段落中句子的數量

不過,我需要它來爲複雜的句子,如工作:

「學習Ruby是一個很大的努力!!!!那麼,它可有時很難......」

在這裏你可以看到標點符號重複出現。

我有什麼,到目前爲止,與簡單的句子作品:

def count_sentences 
    sentence_array = self.split(/[.?!]/) 
    return sentence_array.count 
end 

謝謝!

回答

2

這是很容易適應你的代碼要多一點寬容:

def count_sentences 
    self.split(/[.?!]+/).count 
end 

沒有必要的中間變量或return

注意空字符串也將在此被抓起來,所以你可能要篩選出那些:

test = "This is junk! There's a space at the end! " 

這將與您的代碼返回3。這裏有一個解決方案:

def count_sentences 
    self.split(/[.?!]+/).grep(/\S/).count 
end 

這將只選擇那些至少有一個非空格字符的字符串。

+0

謝謝,非常詳細的答案,它的工作原理!我之前玩過+但由於某種原因無法正常工作...... – alexnewby

+0

它只是意味着「一個或多個」的東西,儘管它會綁定到直接設置,字母或分組,而不是沒有一些輔導的整個單詞。'狗+'匹配「狗」和「狗狗」而不是「狗狗」,而「(?:狗)+」與重複實例匹配。 – tadman

3
class String 
    def count_sentences 
    scan(/[.!?]+(?=\s|\z)/).size 
    end 
end 

str = "Learning Ruby is great!!!! The course cost $2.43... How much??!" 

str.count_sentences 
    #=> 3 

(?=\s|\z)/)正先行,需要匹配緊跟一個空白字符或字符串的末尾。

1

字符串數量可能是最簡單的。

"Who will treat me to a beer? I bet, alexnewby will!".count('.!?') 

與tadman的解決方案相比,不需要構建中間數組。但是,如果,例如,句號或感嘆號的運行是在字符串中找到它產生不正確的結果:

"Now thinking .... Ah, that's it! This is what we have to do!!!".count('.!?') 

=> 8

的問題因此是:你需要絕對的,確切的結果,或者只是近似的(如果這用於統計分析大型印刷文本,這可能就足夠了)?如果你需要確切的結果,你需要定義,什麼是句子,什麼不是。想想下面的文字 - 它有多少句子?

Louise jumped out of the ground floor window. 
"Stop! Don't run away!", cried Andy. "I did not 
want to eat your chocolate; you have to believe 
me!" - and, after thinking for a moment, he 
added: "If you come back, I'll buy you a new 
one! Large one! With hazelnuts!". 

順便說一句,即使tadman的解決方案並不準確。它會給以下單個句子五個計數:

The IP address of Mr. Sloopsteen's dishwasher is 192.168.101.108!