计算Java字符串中的句子数

时间:2018-08-15 15:10:55

标签: java string

您好,到目前为止,我想计算字符串中的句子数:

int count = str.split("[!?.:]+").length;

但是我的字符串包含“。”在名称和单词之间,例如

“他叫Walton D.C.,去年刚完成B.Tech。”

现在使用上一行作为示例计数将返回4个句子,但是只有一个。

那么如何处理这些情况?

4 个答案:

答案 0 :(得分:3)

您可以使用BreakIterator,并检测不同种类的text boundaries

就您而言,句子:

private static void markBoundaries(String target, BreakIterator iterator) {
    StringBuffer markers = new StringBuffer();
    markers.setLength(target.length() + 1);
    for (int k = 0; k < markers.length(); k++) {
        markers.setCharAt(k, ' ');
    }
    int count = 0;
    iterator.setText(target);
    int boundary = iterator.first();
    while (boundary != BreakIterator.DONE) {
        markers.setCharAt(boundary, '^');
        ++count;
        boundary = iterator.next();
    }
    System.out.println(target);
    System.out.println(markers);
    System.out.println("Number of Boundaries: " + count);
    System.out.println("Number of Sentences: " + (count-1));
}

public static void main(String[] args) {
    Locale currentLocale = new Locale("en", "US");
    BreakIterator sentenceIterator
            = BreakIterator.getSentenceInstance(currentLocale);
    String someText = "He name is Walton D.C. and he just completed his B.Tech last year.";
    markBoundaries(someText, sentenceIterator);
    someText = "This order was placed for QT3000! MK?";
    markBoundaries(someText, sentenceIterator);

}

输出将是:

He name is Walton D.C. and he just completed his B.Tech last year.
^                                                                 ^
Number of Boundaries: 2
Number of Sentences: 1
This order was placed for QT3000! MK?
^                                 ^  ^
Number of Boundaries: 3
Number of Sentences: 2

答案 1 :(得分:1)

解决方案可以是在出现点的情况下,您可以检查u后面是否有空格和大写字母。

“ [点] [空格] [大写字母]”

那肯定是对句子的保证

更新相同的代码:

public static void main( String args[] ) {
      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! MK? \n Thats amazing. \n But I am not sure.";
  String pattern = "([.!?])([\\s\\n])([A-Z]*)";

  // Create a Pattern object
  Pattern r = Pattern.compile(pattern);

  // Now create matcher object.
  Matcher m = r.matcher(line);
  int count=0;
  while (m.find( )) {
      count++;
  }
  count++; //for the last line, which will not get included here.
  System.out.println("COUNT=="+count);
}

答案 2 :(得分:0)

一种解决方法是,如果您之前有一个或多个UPERCASE字母,则跳过点。在这种情况下,名称(如果大写)。实现这一点,您将只有一句话。

另一种解决方案:在这里改善一个答案可能是:[小写]([点]或[?]或[!])[空格] [大写]

但是就像我说的那样,如果没有确切的规则,那几乎是不可能的。

答案 3 :(得分:0)

简便的方法

公共类CountLines {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s="Find the number Sentence";
    int count=0;
    for (int i = 0; i < s.length(); i++) {
        if(s.charAt(i)==' ') {
            count++;
        }
    }
    count=count+1;
    System.out.println(count);
}

}