为了账号安全,请及时绑定邮箱和手机立即绑定

计算java字符串中的句子数

计算java字符串中的句子数

慕妹3146593 2021-07-13 17:14:11
我想计算一个字符串中的句子数,到目前为止我正在使用这个:int count = str.split("[!?.:]+").length;但我的字符串包含“。” 例如在名字和单词之间“他的名字是 Walton DC,他去年刚刚完成了他的 B.Tech。”现在使用上面的行作为示例 count 将返回 4 个句子,但只有一个。那么如何应对这些情况呢?
查看完整描述

3 回答

?
森栏

TA贡献1810条经验 获得超5个赞

您可以使用BreakIterator,并检测不同类型的文本边界


在你的情况下句子:


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


查看完整回答
反对 回复 2021-07-23
?
繁星coding

TA贡献1797条经验 获得超4个赞

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


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


这将是对判决的肯定


更新相同的代码:


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);

}


查看完整回答
反对 回复 2021-07-23
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

简单的方法


公共类计数线{


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);

}

}


查看完整回答
反对 回复 2021-07-23
  • 3 回答
  • 0 关注
  • 154 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信