Split text into sentences in C#

前端 未结 4 502
栀梦
栀梦 2020-12-14 12:39

I want to divide a text into sentences. A sentence ends with (dot) or ? or ! followed by one or more whitespace characters followed and the next sentence starts with an uppe

相关标签:
4条回答
  • 2020-12-14 13:02

    Have you tried String.Split()? See the docs about it here

    0 讨论(0)
  • 2020-12-14 13:09

    What languages do you want to support? For example, in Thai there are no spaces between words and sentences are separated with space. So, in general, this task is very complex. Also consider the useful comment by Fredrik Mörk.

    So, at first you need to define set of rules on what "sentence" is. Then you are welcome to use one of the suggested solutions.

    0 讨论(0)
  • 2020-12-14 13:18

    You can split on a regular expression that matches white space, with a lookbehind that looks for the sentence terminators:

    string[] sentences = Regex.Split(input, @"(?<=[\.!\?])\s+");
    

    This will split on the white space characters and keep the terminators in the sentences.

    Example:

    string input = "First sentence. Second sentence! Third sentence? Yes.";
    string[] sentences = Regex.Split(input, @"(?<=[\.!\?])\s+");
    
    foreach (string sentence in sentences) {
      Console.WriteLine(sentence);
    }
    

    Output:

    First sentence.
    Second sentence!
    Third sentence?
    Yes.
    
    0 讨论(0)
  • 2020-12-14 13:26

    Try this (MSDN)

    char[] separators = new char[] {'!', '.', '?'};
    string[] sentences1 = "First sentence. Second sentence!".Split(separators);
    //or...
    string[] sentences2 = "First sentence. Second sentence!".Split('!', '.', '?');
    
    0 讨论(0)
提交回复
热议问题