最近公司在做一個題庫的功能,需要用到 中文分詞和公式分詞的工具,最開始用 ikanalyzer 2012f
版本 + lunece 6.5.1
做了一版中文分詞工具。
具體如下:
一、ikanalyzer 2012f + lunece 6.5.1 實現(xiàn)中文分詞
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public static list<string> analysisbyik(analyzer analyzer,string field, string content){ if (stringutils.isnullorempty(content)){ return null ; } tokenstream ts = null ; try { ts = analyzer.tokenstream(field, new stringreader(content)); chartermattribute term = ts.addattribute(chartermattribute. class ); ts.reset(); list<string> vocabularies = new arraylist<>(); while (ts.incrementtoken()) { vocabularies.add(term.tostring()); } ts.end(); return vocabularies; } catch (exception e) { logger.error(e.getmessage(), e); } finally { if (ts != null ) { try { ts.close(); } catch (ioexception e) { e.printstacktrace(); } } } return null ; } |
調用方式:
1
2
3
4
|
string str = "已知三角形abc中,角a等于角b加角c,那么三角形abc是 a、銳角三角形 b、直角三角形 c、鈍角三角形 d、不能確定" ; analyzer analyzer = new ikanalyzer( true ); iklist = analysisbyik(analyzer, "myfield" , str); listanalyzer.addall(iklist); |
輸出結果listanalyzerd
:
[已知, 三角形, abc, 中, 角, a, 等于, 角, b, 加, 角, c, 那么, 三角形, abc, 是, a, 銳角三角形, b, 直角三角形, c, 鈍角三角形, d, 不能, 確定]
但是由于公式切詞是 原來公司大牛寫的,在滿足公式切詞的條件下,中文切詞的ikanalyzer 2012f
與其不兼容。于是嘗試其他版本,最終決定用 ikanalyzer 3.2.8
實現(xiàn)了兼容。
二、ikanalyzer 3.2.8 + lunece 3.1.0 兼容版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public static list<string> analysisbyik3point2(analyzer analyzer,string field, string content) throws exception{ if (stringutils.isnullorempty(content)){ return null ; } list<string> list = new arraylist<>(); reader reader = new stringreader(content); tokenstream stream = (tokenstream)analyzer.tokenstream(field, reader); //添加工具類 注意:以下這些與之前l(fā)ucene2.x版本不同的地方 termattribute termatt = (termattribute)stream.addattribute(termattribute. class ); offsetattribute offatt = (offsetattribute)stream.addattribute(offsetattribute. class ); // 循環(huán)打印出分詞的結果,及分詞出現(xiàn)的位置 while (stream.incrementtoken()){ list.add(termatt.term()); // system.out.println(termatt.term()); } return list; } |
調用方式:
1
2
3
4
|
string str = "已知三角形abc中,角a等于角b加角c,那么三角形abc是 a、銳角三角形 b、直角三角形 c、鈍角三角形 d、不能確定" ; analyzer analyzer = new ikanalyzer( true ); iklist = analysisbyik3point2(analyzer, "myfield" , str); listanalyzer.addall(iklist); |
輸出結果:
[已知, 三角形, abc, 中, 角, a, 等于, 角, b, 加, 角, c, 那么, 三角形, abc, 是, a, 銳角三角形, b, 直角三角形, c, 鈍角三角形, d, 不能, 確定]
即使用不同版本實現(xiàn)相同功能效果。 主要是 因為ikanalyzer 2012f
依賴analyzer
的tokenstream
是final
方法,但是公式分詞用到的tokensteam
方法是抽象方法。兩者沖突了,所以考慮去做兼容。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/moneyshi/article/details/78645590