HanLP是由一系列模型与算法组成的工具包,目标是普及自然语言处理在生产环境中的应用。HanLP具备功能完善、性能高效、架构清晰、语料时新、可自定义的特点;提供词法分析(中文分词、词性标注、命名实体识别)、句法分析、文本分类和情感分析等功能。

官方文档:https://github.com/hankcs/HanLP

Java1.X官方文档:https://github.com/hankcs/HanLP/tree/1.x

data-for-1.7.5.zip下载地址:
https://github.com/hankcs/HanLP/releases/tag/v1.7.5

项目结构

HanLP分词与jieba分词特点 hanlp分词原理_java

该项目中,.jar和data文件夹和.properties需要下载。

项目配置

HanLP分词与jieba分词特点 hanlp分词原理_HanLP分词与jieba分词特点_02


配置文件的作用是告诉HanLP数据包的位置,只需修改第一行:

root=usr/home/HanLP/为data的 父目录 即可,比如data目录是 /Users/hankcs/Documents/data ,那么 root=/Users/hankcs/Documents/ 。

测试代码

File file = new File("D:/eclipse-workspace/HanLP/a.txt");// Test文件
		File file2 = new File("D:/eclipse-workspace/HanLP/aend.txt");
		
		BufferedReader br = new BufferedReader(new FileReader(file));
		String str = null;
		PrintWriter pw = new PrintWriter(file2);
		
		while((str = br.readLine()) != null) {
			ArrayList<String> aList = new ArrayList();
			StringBuilder sb = new StringBuilder();
			HanLP.Config.ShowTermNature = false; // 关闭词性显示
			List<Term> termList = HanLP.segment(str);
     		for(int i=0;i<termList.size();i++) {
				aList.add(termList.get(i).toString());
			}
			System.out.println(termList);
			for( int i =0;i<aList.size();i++) {
				sb.append(aList.get(i));
				sb.append(" ");
				sb.toString();
			}
			pw.print(sb);
  	     	pw.write("\r\n");
			pw.flush();	
		}
		pw.close();
		br.close();

本测试代码主要是读取TXT文件,通过HanLP进行分词处理之后再输出到TXT文件中。