11大Java开源中文分词器,不同的分词器有不同的用法,定义的接口也不一样,我们先定义一个统一的接口:
/**
* 获取文本的所有分词结果, 对比不同分词器结果
*/
public interface WordSegmenter {
/**
* 获取文本的所有分词结果
* @param text 文本
* @return 所有的分词结果,去除重复
*/
default public Set<String> seg(String text) {
return segMore(text).values().stream().collect(Collectors.toSet());
}
/**
* 获取文本的所有分词结果
* @param text 文本
* @return 所有的分词结果,KEY 为分词器模式,VALUE 为分词器结果
*/
public Map<String, String> segMore(String text);
}
从上面的定义我们知道,在Java中,同样的方法名称和参数,但是返回值不同,这种情况不可以使用重载。
这两个方法的区别在于返回值,每一个分词器都可能有多种分词模式,每种模式的分词结果都可能不相同,第一个方法忽略分词器模式,返回所有模式的所有不重复分词结果,第二个方法返回每一种分词器模式及其对应的分词结果。
在这里,需要注意的是我们使用了Java8中的新特性默认方法,并使用stream把一个map的value转换为不重复的集合。
下面我们利用这11大分词器来实现这个接口:
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
for(SegmentationAlgorithm segmentationAlgorithm : SegmentationAlgorithm.values()){
map.put(segmentationAlgorithm.getDes(), seg(text, segmentationAlgorithm));
}
return map;
}
private static String seg(String text, SegmentationAlgorithm segmentationAlgorithm) {
StringBuilder result = new StringBuilder();
for(Word word : WordSegmenter.segWithStopWords(text, segmentationAlgorithm)){
result.append(word.getText()).append(" ");
}
return result.toString();
}
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
StringBuilder result = new StringBuilder();
for(Term term : BaseAnalysis.parse(text)){
result.append(term.getName()).append(" ");
}
map.put("BaseAnalysis", result.toString());
result.setLength(0);
for(Term term : ToAnalysis.parse(text)){
result.append(term.getName()).append(" ");
}
map.put("ToAnalysis", result.toString());
result.setLength(0);
for(Term term : NlpAnalysis.parse(text)){
result.append(term.getName()).append(" ");
}
map.put("NlpAnalysis", result.toString());
result.setLength(0);
for(Term term : IndexAnalysis.parse(text)){
result.append(term.getName()).append(" ");
}
map.put("IndexAnalysis", result.toString());
return map;
}
private static final StanfordCoreNLP CTB = new StanfordCoreNLP("StanfordCoreNLP-chinese-ctb");
private static final StanfordCoreNLP PKU = new StanfordCoreNLP("StanfordCoreNLP-chinese-pku");
private static final PrintStream NULL_PRINT_STREAM = new PrintStream(new NullOutputStream(), false);
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("Stanford Beijing University segmentation", seg(PKU, text));
map.put("Stanford Chinese Treebank segmentation", seg(CTB, text));
return map;
}
private static String seg(StanfordCoreNLP stanfordCoreNLP, String text){
PrintStream err = System.err;
System.setErr(NULL_PRINT_STREAM);
Annotation document = new Annotation(text);
stanfordCoreNLP.annotate(document);
List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
StringBuilder result = new StringBuilder();
for(CoreMap sentence: sentences) {
for (CoreLabel token: sentence.get(CoreAnnotations.TokensAnnotation.class)) {
String word = token.get(CoreAnnotations.TextAnnotation.class);;
result.append(word).append(" ");
}
}
System.setErr(err);
return result.toString();
}
private static CWSTagger tagger = null;
static{
try{
tagger = new CWSTagger("lib/fudannlp_seg.m");
tagger.setEnFilter(true);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("FudanNLP", tagger.tag(text));
return map;
}
private static final JiebaSegmenter JIEBA_SEGMENTER = new JiebaSegmenter();
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("INDEX", seg(text, SegMode.INDEX));
map.put("SEARCH", seg(text, SegMode.SEARCH));
return map;
}
private static String seg(String text, SegMode segMode) {
StringBuilder result = new StringBuilder();
for(SegToken token : JIEBA_SEGMENTER.process(text, segMode)){
result.append(token.word.getToken()).append(" ");
}
return result.toString();
}
private static final JcsegTaskConfig CONFIG = new JcsegTaskConfig();
private static final ADictionary DIC = DictionaryFactory.createDefaultDictionary(CONFIG);
static {
CONFIG.setLoadCJKSyn(false);
CONFIG.setLoadCJKPinyin(false);
}
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("复杂模式", segText(text, JcsegTaskConfig.COMPLEX_MODE));
map.put("简易模式", segText(text, JcsegTaskConfig.SIMPLE_MODE));
return map;
}
private String segText(String text, int segMode) {
StringBuilder result = new StringBuilder();
try {
ISegment seg = SegmentFactory.createJcseg(segMode, new Object[]{new StringReader(text), CONFIG, DIC});
IWord word = null;
while((word=seg.next())!=null) {
result.append(word.getValue()).append(" ");
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return result.toString();
}
private static final Dictionary DIC = Dictionary.getInstance();
private static final SimpleSeg SIMPLE_SEG = new SimpleSeg(DIC);
private static final ComplexSeg COMPLEX_SEG = new ComplexSeg(DIC);
private static final MaxWordSeg MAX_WORD_SEG = new MaxWordSeg(DIC);
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put(SIMPLE_SEG.getClass().getSimpleName(), segText(text, SIMPLE_SEG));
map.put(COMPLEX_SEG.getClass().getSimpleName(), segText(text, COMPLEX_SEG));
map.put(MAX_WORD_SEG.getClass().getSimpleName(), segText(text, MAX_WORD_SEG));
return map;
}
private String segText(String text, Seg seg) {
StringBuilder result = new StringBuilder();
MMSeg mmSeg = new MMSeg(new StringReader(text), seg);
try {
Word word = null;
while((word=mmSeg.next())!=null) {
result.append(word.getString()).append(" ");
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return result.toString();
}
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("智能切分", segText(text, true));
map.put("细粒度切分", segText(text, false));
return map;
}
private String segText(String text, boolean useSmart) {
StringBuilder result = new StringBuilder();
IKSegmenter ik = new IKSegmenter(new StringReader(text), useSmart);
try {
Lexeme word = null;
while((word=ik.next())!=null) {
result.append(word.getLexemeText()).append(" ");
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return result.toString();
}
private static final PaodingAnalyzer ANALYZER = new PaodingAnalyzer();
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("MOST_WORDS_MODE", seg(text, PaodingAnalyzer.MOST_WORDS_MODE));
map.put("MAX_WORD_LENGTH_MODE", seg(text, PaodingAnalyzer.MAX_WORD_LENGTH_MODE));
return map;
}
private static String seg(String text, int mode){
ANALYZER.setMode(mode);
StringBuilder result = new StringBuilder();
try {
Token reusableToken = new Token();
TokenStream stream = ANALYZER.tokenStream("", new StringReader(text));
Token token = null;
while((token = stream.next(reusableToken)) != null){
result.append(token.term()).append(" ");
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return result.toString();
}
private static final SmartChineseAnalyzer SMART_CHINESE_ANALYZER = new SmartChineseAnalyzer();
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("smartcn", segText(text));
return map;
}
private static String segText(String text) {
StringBuilder result = new StringBuilder();
try {
TokenStream tokenStream = SMART_CHINESE_ANALYZER.tokenStream("text", new StringReader(text));
tokenStream.reset();
while (tokenStream.incrementToken()){
CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class);
result.append(charTermAttribute.toString()).append(" ");
}
tokenStream.close();
}catch (Exception e){
e.printStackTrace();
}
return result.toString();
}
private static final Segment N_SHORT_SEGMENT = new NShortSegment().enableCustomDictionary(false).enablePlaceRecognize(true).enableOrganizationRecognize(true);
private static final Segment DIJKSTRA_SEGMENT = new DijkstraSegment().enableCustomDictionary(false).enablePlaceRecognize(true).enableOrganizationRecognize(true);
@Override
public Map<String, String> segMore(String text) {
Map<String, String> map = new HashMap<>();
map.put("标准分词", standard(text));
map.put("NLP分词", nlp(text));
map.put("索引分词", index(text));
map.put("N-最短路径分词", nShort(text));
map.put("最短路径分词", shortest(text));
map.put("极速词典分词", speed(text));
return map;
}
private static String standard(String text) {
StringBuilder result = new StringBuilder();
StandardTokenizer.segment(text).forEach(term->result.append(term.word).append(" "));
return result.toString();
}
private static String nlp(String text) {
StringBuilder result = new StringBuilder();
NLPTokenizer.segment(text).forEach(term->result.append(term.word).append(" "));
return result.toString();
}
private static String index(String text) {
StringBuilder result = new StringBuilder();
IndexTokenizer.segment(text).forEach(term->result.append(term.word).append(" "));
return result.toString();
}
private static String speed(String text) {
StringBuilder result = new StringBuilder();
SpeedTokenizer.segment(text).forEach(term->result.append(term.word).append(" "));
return result.toString();
}
private static String nShort(String text) {
StringBuilder result = new StringBuilder();
N_SHORT_SEGMENT.seg(text).forEach(term->result.append(term.word).append(" "));
return result.toString();
}
private static String shortest(String text) {
StringBuilder result = new StringBuilder();
DIJKSTRA_SEGMENT.seg(text).forEach(term->result.append(term.word).append(" "));
return result.toString();
}
动宝儿欢迎各位大牛和同学们补充和指正,到哪里系统的学习Java,动宝儿推荐,多年大型企业项目经验的大牛导师会一站式解决你对Java学习的所有困惑,不信就来试听。