2012-02-05 140 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