Java如何将文本或句子分解为单词?
起初,它看起来很简单。我们可以使用来分割文本String.split(),使用空格来分割单词。但是,如果单词以问号(?)或感叹号(!)结尾,该怎么办?我们可能还需要注意其他一些规则。
使用java.text.BreakIterator使变得更加简单。该类的getWordInstance()工厂方法BreakIterator为单词break创建一个实例。实例化aBreakIterator并传递语言环境信息会使迭代器根据语言环境的规则来中断文本或句子。当我们使用复杂的语言(例如日语或中文)时,这确实很有帮助。
让我们来看一个使用BreakIterator下面的例子。
package org.nhooo.example.text;
import java.text.BreakIterator;
import java.util.Locale;
public class BreakIteratorExample {
public static void main(String[] args) {
String data = "The quick brown fox jumps over the lazy dog.";
String search = "dog";
//获取BreakIterator的实例,以用于
//给定的语言环境。我们可以实例化BreakIterator而无需
//指定语言环境。当我们
//正在使用日语或中文等语言
//与英语相比,休息标准可能有所不同。
BreakIterator bi = BreakIterator.getWordInstance(Locale.US);
//设置要扫描的文本字符串。
bi.setText(data);
//迭代边界/中断
System.out.println("Iterates each word: ");
int count = 0;
int lastIndex = bi.first();
while (lastIndex != BreakIterator.DONE) {
int firstIndex = lastIndex;
lastIndex = bi.next();
if (lastIndex != BreakIterator.DONE
&& Character.isLetterOrDigit(data.charAt(firstIndex))) {
String word = data.substring(firstIndex, lastIndex);
System.out.printf("'%s' found at (%s, %s)%n", word, firstIndex, lastIndex);
//计算“狗”一词出现的次数。
if (word.equalsIgnoreCase(search)) {
count++;
}
}
}
System.out.println("Number of word '" + search + "' found = " + count);
}
}这是程序输出:
Iterates each word: 'The' found at (0, 3) 'quick' found at (4, 9) 'brown' found at (10, 15) 'fox' found at (16, 19) 'jumps' found at (20, 25) 'over' found at (26, 30) 'the' found at (31, 34) 'lazy' found at (35, 39) 'dog' found at (40, 43) Number of word 'dog' found = 1
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短