段落分句Java,Java如何将段落分成句子?

本示例说明如何使用BreakIterator.getSentenceInstance()来将段落分为组成该段落的句子。要获取BreakIterator实例,我们调用getSentenceInstance()factory方法并传递语言环境信息。

在该count(BreakIterator bi, String source)方法中,我们迭代中断以提取组成该段落的句子,该段落的值存储在paragraph变量中。package org.nhooo.example.text;

import java.text.BreakIterator;

import java.util.Locale;

public class BreakSentenceExample {

public static void main(String[] args) {

String paragraph =

"Line boundary analysis determines where a text " +

"string can be broken when line-wrapping. The " +

"mechanism correctly handles punctuation and " +

"hyphenated words. Actual line breaking needs to " +

"also consider the available line width and is " +

"handled by higher-level software. ";

BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US);

int sentences = count(iterator, paragraph);

System.out.println("Number of sentences: " + sentences);

}

private static int count(BreakIterator bi, String source) {

int counter = 0;

bi.setText(source);

int lastIndex = bi.first();

while (lastIndex != BreakIterator.DONE) {

int firstIndex = lastIndex;

lastIndex = bi.next();

if (lastIndex != BreakIterator.DONE) {

String sentence = source.substring(firstIndex, lastIndex);

System.out.println("sentence = " + sentence);

counter++;

}

}

return counter;

}

}

我们的程序将在控制台屏幕上打印以下结果:sentence = Line boundary analysis determines where a text string can be broken when line-wrapping.

sentence = The mechanism correctly handles punctuation and hyphenated words.

sentence = Actual line breaking needs to also consider the available line width and is handled by higher-level software.

Number of sentences: 3

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值