今天在学习Lucene in Action时,书上给出了一段测试Lucene分词器的代码,由于这本书对应的lucene版本非常古老,在Lucene3.0.0版本中,TokenStream类做了较大修改,特别是删除了常用的next()方法,这导致之前常用的许多查看分词结果的代码都不能在lucene3.0中使用。
我尝试修改此例使之在3.0中可以使用,主要的变化在TokenStream取得下一个token的方法。在Lucene3.0.0中TokenStream类完全删除了next方法,改为使用incrementToken()方法推动Token流向下一个位置移动,使用getAttribute得到当前的term项。Attribute是Lucene中新增的(但是是不是3.0.0新增的我就不知道了),用于用户对索引项添加其他一些描述信息。
这个工具也可以从命令行直接指定多个需要进行分析的字符串。若要测试自己写的分词器,只需在AnalyzerDemo中加入对应的分词器即可。
AnalyzerDemo.java
AnalyzerUtils.java
测试输出为:
Analyzing "The quick brown fox jumped over the lazy dogs"
WhitespaceAnalyzer:
[The] [quick] [brown] [fox] [jumped] [over] [the] [lazy] [dogs]
SimpleAnalyzer:
[the] [quick] [brown] [fox] [jumped] [over] [the] [lazy] [dogs]
StopAnalyzer:
[quick] [brown] [fox] [jumped] [over] [lazy] [dogs]
StandardAnalyzer:
[quick] [brown] [fox] [jumped] [over] [lazy] [dogs]
Analyzing "XY&Z Corporation - xyz@example.com"
WhitespaceAnalyzer:
[XY&Z] [Corporation] [-] [xyz@example.com]
SimpleAnalyzer:
[xy] [z] [corporation] [xyz] [example] [com]
StopAnalyzer:
[xy] [z] [corporation] [xyz] [example] [com]
StandardAnalyzer:
[xy&z] [corporation] [xyz@example.com]
Analyzing "这是一个简单的lucene分词测试工具"
WhitespaceAnalyzer:
[这是一个简单的lucene分词测试工具]
SimpleAnalyzer:
[这是一个简单的lucene分词测试工具]
StopAnalyzer:
[这是一个简单的lucene分词测试工具]
StandardAnalyzer:
[这] [是] [一] [个] [简] [单] [的] [lucene] [分] [词] [测] [试] [工] [具]