字符串數量可能是最簡單的。
"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!
謝謝,非常詳細的答案,它的工作原理!我之前玩過+但由於某種原因無法正常工作...... – alexnewby
它只是意味着「一個或多個」的東西,儘管它會綁定到直接設置,字母或分組,而不是沒有一些輔導的整個單詞。'狗+'匹配「狗」和「狗狗」而不是「狗狗」,而「(?:狗)+」與重複實例匹配。 – tadman