2012-02-05 136 views
2

如何計算給定字符串中的句子數?計算字符串中的句子數

+7

取決於「句子」的定義以及字符串究竟是什麼。 – 2012-02-05 17:21:35

+4

你到目前爲止嘗試過什麼?這些句子可能包含什麼?他們是否總是以「。」結尾,或者可能是問號/感嘆號等?他們可能包含有小數點的數字嗎? – 2012-02-05 17:21:51

+0

計算'.','?','!'的數量 – 2012-02-05 17:23:36

回答

7

如果您已經安裝了Word,您可以使用Word interop來獲取句子計數以及其他統計信息。這也有可能與除英語之外的其他語言一起工作的好處。

object oMissing = System.Reflection.Missing.Value; 

var oWord = new Microsoft.Office.Interop.Word.Application(); 
oWord.Visible = false; 
var oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

oDoc.Content.Text = inputTextBox.Text; 

//get just sentence count 
sentenceCountLabel.Text = oDoc.Sentences.Count.ToString(); 

//get all statistics 
foreach (Microsoft.Office.Interop.Word.ReadabilityStatistic stat in oDoc.ReadabilityStatistics) 
{ 
    Console.WriteLine("{0}: {1}", stat.Name, stat.Value); 
} 

object oFalse = false; 

oDoc.Close(ref oFalse, ref oMissing, ref oMissing); 

這將輸出:

Words: 283 
Characters: 1271 
Paragraphs: 3 
Sentences: 6 
Sentences per Paragraph: 2 
Words per Sentence: 47.1 
Characters per Word: 4.3 
Passive Sentences: 0 
Flesch Reading Ease: 55.2 
Flesch-Kincaid Grade Level: 12.5 

這可能不是最有效的,但只需要幾行代碼,並且可以適當根據您的需要。

+0

非常感謝這個例子。這正是我所期待的。十分感謝。 – 2012-02-05 19:17:43

12

您需要一個自然語言解析庫。

例如,您可以使用這是OpenNLP項目的C#端口。

SharpNLP是用C#編寫的自然語言處理工具的集合。目前,它提供了以下NLP工具:

  • 一句分流
  • 等...

文章Statistical parsing of English sentences對如何安裝和使用的句子探測器SharpNLP一些細節。下面重複該文章的示例代碼作爲傳情,但請閱讀文檔以獲取有關可用功能以及如何使用功能的更完整說明。

using OpenNLP.Tools.SentenceDetect; 

// ... 

EnglishMaximumEntropySentenceDetector sentenceDetector = 
    new EnglishMaximumEntropySentenceDetector(mModelPath + "EnglishSD.nbin"); 
string[] sentences = sentenceDetector.SentenceDetect(input); 

如果你可以假設你的句子一個簡單的規則,如在一段時間他們都結束,出現了一段無處除了形式在句子的末尾,那麼你可以改爲只請計算文本中的句號數。但請注意,英文文本通常不適合此模式,因爲:

  • 還有其他字符可以使句子結束句子。
  • 除了結束句子之外,英語還有其他用途。
+0

其他地方可能有點 - 我試圖實施Flesch-Kincaid可讀性測試。 – 2012-02-05 17:34:51

+0

@LukeG你可能不得不使用微軟Word互操作,如你的其他問題的答案建議http://stackoverflow.com/questions/9151097/flesch-kincaid-readability-test – 2012-02-05 17:46:37

+0

@羅伊古德好點,我更新了我的答案演示如何訪問所有文檔統計信息。 – 2012-02-05 17:51:25