HanLP中文分詞Lucene外掛

adnb34g發表於2019-04-15

  基於 HanLP,支援包括Solr(7.x)在內的任何基於Lucene(7.x)的系統。

 

Maven

    <dependency>

      <groupId>com.hankcs.nlp</groupId>

      <artifactId>hanlp-lucene-plugin</artifactId>

      <version>1.1.6</version>

    </dependency>

Solr快速上手

1. hanlp-portable.jar和hanlp-lucene-plugin.jar共兩個jar放入${webapp}/WEB-INF/lib下。(或者使用mvn package對原始碼打包,拷貝target/hanlp-lucene-plugin-x.x.x.jar到${webapp}/WEB-INF/lib下)

2. 修改 solr core的配置檔案${core}/conf/schema.xml:

  <fieldType name="text_cn" class="solr.TextField">

      <analyzer type="index">

          <tokenizer class="com.hankcs.lucene.HanLPTokenizerFactory" enableIndexMode="true"/>

      </analyzer>

      <analyzer type="query">

          <!-- 切記不要在query中開啟index模式 -->

          <tokenizer class="com.hankcs.lucene.HanLPTokenizerFactory" enableIndexMode="false"/>

      </analyzer>

  </fieldType>

  <!-- 業務系統中需要分詞的欄位都需要指定type為text_cn -->

  <field name="my_field1" type="text_cn" indexed="true" stored="true"/>

  <field name="my_field2" type="text_cn" indexed="true" stored="true"/>

· 如果你的業務系統中有其他欄位,比如 location,summary之類,也需要一一指定其type="text_cn"。切記,否則這些欄位仍舊是solr預設分詞器。

· 另外,切記不要在 query中開啟indexMode,否則會影響PhaseQuery。indexMode只需在index中開啟一遍即可。

高階配置

目前本外掛支援如下基於 schema.xml的配置:

 

 

更高階的配置主要通過 class path下的hanlp.properties進行配置,請閱讀HanLP自然語言處理包文件以瞭解更多相關配置,如:

 

0. 使用者詞典

1. 詞性標註

2. 簡繁轉換

3. ……

停用詞與同義詞

 

推薦利用 Lucene或Solr自帶的filter實現,本外掛不會越俎代庖。 一個示例配置如下:

 

 

呼叫方法

Query改寫的時候,可以利用HanLPAnalyzer分詞結果中的詞性等屬性,如

 

String text = "中華人民共和國很遼闊";

for (int i = 0; i < text.length(); ++i)

{

    System.out.print(text.charAt(i) + "" + i + " ");

}

System.out.println();

Analyzer analyzer = new HanLPAnalyzer();

TokenStream tokenStream = analyzer.tokenStream("field", text);

tokenStream.reset();

while (tokenStream.incrementToken())

{

    CharTermAttribute attribute = tokenStream.getAttribute(CharTermAttribute.class);

    // 偏移量

    OffsetAttribute offsetAtt = tokenStream.getAttribute(OffsetAttribute.class);

    // 距離

    PositionIncrementAttribute positionAttr = tokenStream.getAttribute(PositionIncrementAttribute.class);

    // 詞性

    TypeAttribute typeAttr = tokenStream.getAttribute(TypeAttribute.class);

    System.out.printf("[%d:%d %d] %s/%s\n", offsetAtt.startOffset(), offsetAtt.endOffset(), positionAttr.getPositionIncrement(), attribute, typeAttr.type());

}

在另一些場景,支援以自定義的分詞器(比如開啟了命名實體識別的分詞器、繁體中文分詞器、 CRF分詞器等)構造HanLPTokenizer,比如:

 

tokenizer = new HanLPTokenizer(HanLP.newSegment()

                                    .enableJapaneseNameRecognize(true)

                                    .enableIndexMode(true), null, false);

tokenizer.setReader(new StringReader("林志玲亮相網友:確定不是波多野結衣?"));

文章摘自: 2019 github

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31524777/viewspace-2641378/,如需轉載,請註明出處,否則將追究法律責任。

相關文章