中文分詞需要實現(xiàn)功能確實可以自己寫,但是效率會很低,現(xiàn)在互聯(lián)網(wǎng)的時代很多已經(jīng)寫好的分詞引擎,我們只需會用就行:
當前熱門的分詞引擎:11款開放中文分詞引擎大比拼
而今天我要講的是對分詞引擎進行封裝了的中文分詞封裝-TokenizerUtil 真的超級好用只需兩步即可實現(xiàn)中文分詞:
第一步TokenizerUtil工具的引入:
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.0</version></dependency>
第二步選擇要用的引擎引入:
<dependency>
<groupId>org.ansj</groupId>
<artifactId>ansj_seg</artifactId>
<version>5.1.1</version>
</dependency>
第三步使用工具類:
//初始化分詞引擎
TokenizerEngine engine = TokenizerUtil.createEngine();
//解析文本
Result errorResult = engine.parse(errorText);
String errorParticipleStr = CollUtil.join((Iterator<Word>) errorResult, ",");
錯誤分詞結果,只能使用此方式迭代為新字符串
以上就能實現(xiàn)中文分詞后續(xù)項目的開發(fā)就可根據(jù)實際需要自行操作分詞結果
向我就是對分詞結果再重組看某個錯詞是否是真的錯詞:
Result checkResult = engine.parse(checkText);
String checkParticipleStr = CollUtil.join((Iterator<Word>) checkResult, ",");
System.out.println(checkParticipleStr);
String[] checkParticipleStrArr = checkParticipleStr.split(",");//分詞后的字符串數(shù)組
List<String> result = new ArrayList<>();
if (checkParticipleStrArr.length > 0) {
for(int i = 0; i < checkParticipleStrArr.length; i++) {//從左往右按順序重組即可
if (checkParticipleStrArr.length -i < errorStep) break;//開始位置后的個數(shù)小于步長跳出
StringBuilder temp = new StringBuilder();
temp.append(checkParticipleStrArr[i]);
int dep = 1;
while (errorStep > dep) {
temp.append(checkParticipleStrArr[i + dep]);//根據(jù)步長取相應個數(shù)的字符串
dep++;
}
System.out.println(temp.toString());
result.add(temp.toString());
}
}





暫無評論,快來評論吧!