2011-11-05 49 views
1

我有這樣的一個文本: 「這是句子1.這是句子2.是這個句子3?hello world!」Preg_split句子中保存標點符號

我使用此代碼將文本拆分爲句子並將它們插入到數組中。

$content = $page_data->post_content; 
    $sentence = preg_split('/[!?\.]\s?/', $content); 
    $sentence = array_map('trim', $sentence); 
    echo $sentence[0]; - **which renders this is sentence 1 - without the "."** 
    .... 

如何使用此代碼並保留標點符號?

泰:)

+0

在Perl的'split'中,可以使用捕獲組保留分隔符s,但那些顯示爲單獨的元素。如果這就是你想要的,那麼你可以使用全局匹配來實現相同的結果。但是如果你想把它保留在句子的末尾,@codaddict有正確的概念。對於真實世界的數據,你需要更小心一點。是不是有一些現有的圖書館已經爲你做了NLP正確的句子拆分,如[Perl's Lingua :: Sentence](http://search.cpan.org/perldoc?Lingua::句子)?這就是你需要的。 – tchrist

回答

0

您可以使用斷言背後的正面看:

$sentence = preg_split('/(?<=[!?.])./', $content); 

See it

+2

這不適用於有縮寫的句子,你知道。你需要使用更類似於(?<= [!?。])(?:$ | \ s +(?= \ p {Lu} \ p {Ll} * \ b))'的東西,羅傑斯先生等問題。您應該使用經常縮寫的標題的停止列表,但如果不通過類似於輸入流的語料庫上的機器學習引擎運行它,就無法獲得良好的結果,從而無法對這些內容進行培訓。 – tchrist

0

使preg_split有沒有這樣的標誌,這使分隔符,但是,你可以使用preg_match_all:

<?php 

    $content = "this is sentence 1. this is sentence 2. is this sentence 3? hello world!"; 
    preg_match_all('/([^\.\?!]+[\.\?!])/', $content, $sentence); 
    $sentence = array_map('trim', $sentence[0]); 
    print_r($sentence); 

?>