中文分词器
字数: 0 字 时长: 0 分钟
- IK 分词器: 轻量级,性能较好;但分词依赖于词典,对于新词、专有名词的识别能力有限
- HanLP 分词器: 分词效果好,功能丰富,支持多语言;但配置和使用相对复杂,体积大,消耗资源更多
IK 分词器
下载
安装
将压缩包解压到 plugins
目录下即可
配置文件
IKAnalyzer.cfg.xml
: IK 分词配置文件main.dic
: 主词库stopword.dic
: 英文停用词- 特殊词库 :
quantifier.dic
suffix.dic
surname.dic
preposition
等
分词模式
ik_max_word
: 会将文本做最细粒度的拆分,适合 Term Query
json
GET _analyze
{
"analyzer" : "ik_max_word",
"text" : "小米智能手机"
}
{
"tokens": [
{
"token": "小米",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 0
},
{
"token": "智能手机",
"start_offset": 2,
"end_offset": 6,
"type": "CN_WORD",
"position": 1
},
{
"token": "智能",
"start_offset": 2,
"end_offset": 4,
"type": "CN_WORD",
"position": 2
},
{
"token": "能手",
"start_offset": 3,
"end_offset": 5,
"type": "CN_WORD",
"position": 3
},
{
"token": "手机",
"start_offset": 4,
"end_offset": 6,
"type": "CN_WORD",
"position": 4
}
]
}
ik_smart
: 会将文本做最粗粒度的拆分,适合 Phrase Query
json
GET _analyze
{
"analyzer" : "ik_smart",
"text" : "小米智能手机"
}
{
"tokens": [
{
"token": "小米",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 0
},
{
"token": "智能手机",
"start_offset": 2,
"end_offset": 6,
"type": "CN_WORD",
"position": 1
}
]
}
基于本地词库扩展
创建自定义的扩展词库文件,比如 mywords.dic
,然后在 IKAnalyzer.cfg.xml
文件中添加如下配置:
xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>IK Analyzer 扩展配置</comment>
<!--用户可以在这里配置自己的扩展字典 -->
<entry key="ext_dict">mywords.dic</entry>
<!--用户可以在这里配置自己的扩展停止词字典-->
<entry key="ext_stopwords"></entry>
<!--用户可以在这里配置远程扩展字典 -->
<!-- <entry key="remote_ext_dict">words_location</entry> -->
<!--用户可以在这里配置远程扩展停止词字典-->
<!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>
基于远程词库扩展
- 修改配置文件,开启远程词库扩展
xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>IK Analyzer 扩展配置</comment>
<!--用户可以在这里配置自己的扩展字典 -->
<entry key="ext_dict">mywords.dic</entry>
<!--用户可以在这里配置自己的扩展停止词字典-->
<entry key="ext_stopwords"></entry>
<!--用户可以在这里配置远程扩展字典 -->
<entry key="remote_ext_dict">"http://localhost:8080/api/hotWord"</entry>
<!--用户可以在这里配置远程扩展停止词字典-->
<entry key="remote_ext_stopwords"></entry>
</properties>
- java 代码实现远程接口
java
@RequestMapping("/hotWord")
public void hotWords(HttpServletResponse response) throws IOException {
//自定义文件路径
String filePath = "E:\\venti\\venti-ikword\\src\\main\\resources\\hotword.dic";
String content = Files.readString(Paths.get(filePath), StandardCharsets.UTF_8);
response.setContentType("text/plain;charset=UTF-8");
// IK 分词器要求远程扩展词库添加请求头属性
response.setHeader("Last-Modified", String.valueOf(System.currentTimeMillis()));
response.setHeader("ETag", String.valueOf(System.currentTimeMillis()));
try (ServletOutputStream out = response.getOutputStream()){
out.write(content.getBytes(StandardCharsets.UTF_8));
out.flush();
}
}