当前位置: 代码迷 >> 综合 >> Lucene分词器
  详细解决方案

Lucene分词器

热度:68   发布时间:2024-02-06 11:38:26.0

1.分词器概述

分词计算在倒排索引创建的过程中,起着非常重要的作用,不同分词计算需求,使用分词计算规则算法逻辑底层代码完全不相同的。lucene也不能完成世界上所有对分词器需求的计算,所以Lucene提供了分词器接口Analyzer,想要加入Lucene的逻辑,实现这个接口即可。

2.分词器案例

2.1 需要引入依赖

<dependency> <!-- 查询相关jar包 --><groupId>org.apache.lucene</groupId><artifactId>lucene-queryparser</artifactId><version>6.0.0</version></dependency><dependency> <!-- lucene自带只能中文分词器jar包 --><groupId>org.apache.lucene</groupId><artifactId>lucene-analyzers-smartcn</artifactId><version>6.0.0</version></dependency>

2.2 使用不同分词器,实现分词计算打印展示

StandardAnalyzer-->标准分词器

  • 英文:对词做加工,按照空格,标点分开
  • 中文:字做加工

SimpleAnalyzer--->简单分词器

对空格/标点符号进行切分计算

  • 英文:词加工
  • 中文:段逻,句加工

WhitespaceAnalyzer--->空格分词器

  • 按照空格处理数据

SmartChineseAnalyzer--->智能中文分词器

  • 处理常用的中文词语

IKAnalyzer--->中文分词器

对于语言的发展,新的词语的出现,总是改变对分词计算的需求.引入基于词典的分词器---IKAnalzyer.可以对词典进行扩展,计算分词时,读取到词典的数据就可以计算该词语成为一个词项.

还支持停用词典:在停用词典中的词语,不会计算分词

例如: 敏感词,禁语,无意义词语

代码示例:

public class AnalyzerTest {//完成方法,接收文本字符串,通过使用分词器的api将词项的文本属性//打印出来public void printTerm(Analyzer a, String msg) throws Exception {//使用a实现对象,解析msg分词计算;//String原数据转化成流对象StringReader reader=new StringReader(msg);//调用a这个分词的api将read流计算成词项TokenStream token = a.tokenStream("test", reader);//分词不能独立存在,依托document数据token.reset();//拿到当前指针位置的词项的文本属性OffsetAttribute offAttr = token.getAttribute(OffsetAttribute.class);CharTermAttribute charAttr = token.getAttribute(CharTermAttribute.class);while(token.incrementToken()){System.out.println("偏移量起始位置:"+offAttr.startOffset());System.out.println("偏移量结束位置:"+offAttr.endOffset());System.out.println(charAttr.toString());}}@Testpublic void run() throws Exception {//构造多个不同实现类的分词器Analyzer a1=new StandardAnalyzer();Analyzer a2=new SimpleAnalyzer();Analyzer a3=new WhitespaceAnalyzer();Analyzer a4=new SmartChineseAnalyzer();//计算分词的文本字符串String msg="how are you?Fine,thank you!And you?";System.out.println("******************标准********************");printTerm(a1,msg);System.out.println("******************简单********************");printTerm(a2,msg);System.out.println("******************空格********************");printTerm(a3,msg);System.out.println("******************智能********************");printTerm(a4,msg);}}

 

  相关解决方案