java 使用HanLP 入门教程
java 使用HanLP 入门教程
·
1. 安装 HanLP
Maven 依赖
<dependency>
<groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId>
<version>portable-1.8.4</version> <!-- 最新版本请查看官网 -->
</dependency>
注意:
portable版本内置小型词典,适合基础任务;若需完整功能,需下载完整数据包。
2. 基础功能
(1) 分词
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
public class BasicDemo {
public static void main(String[] args) {
String text = "你好,欢迎使用HanLP!这是一段测试文本。";
// 标准分词
List<Term> termList = HanLP.segment(text);
System.out.println(termList);
// 输出: [你好/vl, ,/w, 欢迎/v, 使用/v, HanLP/nx, !/w, 这是/r, 一段/m, 测试/vn, 文本/n, 。/w]
}
}
(2) 词性标注
HanLP 的分词结果已包含词性(如 n=名词,v=动词):
for (Term term : termList) {
System.out.println(term.word + " : " + term.nature);
}
常用词性标记:
n:名词v:动词w:标点符号nx:外文单词
3. 进阶功能
(1) 关键词提取
import com.hankcs.hanlp.summary.TextRankKeyword;
List<String> keywords = HanLP.extractKeyword(text, 5); // 提取前5个关键词
System.out.println(keywords); // 输出: [文本, 测试, HanLP, 欢迎, 使用]
(2) 命名实体识别(NER)
List<Term> termList = HanLP.segment("马云在阿里巴巴工作。");
for (Term term : termList) {
if (term.nature.toString().startsWith("nr")) { // nr=人名
System.out.println("人名: " + term.word);
} else if (term.nature.toString().startsWith("ns")) { // ns=地名
System.out.println("地名: " + term.word);
}
}
// 输出: 人名: 马云 地名: 阿里巴巴
(3) 自定义词典
// 方式1:临时添加单词
HanLP.Config.CustomDictionaryPath = new String[]{"data/dictionary/custom/CustomDictionary.txt"};
HanLP.Config.enableDebug();
// 方式2:动态添加
CustomDictionary.add("量子计算", "n 1024");
CustomDictionary.insert("神经网络", "n 1024");
// 使用自定义词典分词
System.out.println(HanLP.segment("量子计算是未来趋势"));
// 输出: [量子计算/n, 是/v, 未来/t, 趋势/n]
4. 高级配置
(1) 切换分词模式
// 极速词典分词(不标注词性)
List<String> fastSegResult = HanLP.segmentFaster(text);
// 标准分词(带词性)
List<Term> stdSegResult = HanLP.segment(text);
// NLP分词(高精度,需完整数据包)
List<Term> nlpSegResult = HanLP.newSegment().enableNameRecognize(true).seg(text);
(2) 加载完整数据包
- 下载数据包并解压。
- 配置
hanlp.properties:root=path/to/hanlp-data
5. 完整示例
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import java.util.List;
public class HanLPFullDemo {
public static void main(String[] args) {
String text = "清华大学位于北京市海淀区。";
// 分词 + 词性标注
List<Term> terms = HanLP.segment(text);
System.out.println("分词结果: " + terms);
// 命名实体识别
terms = HanLP.newSegment().enablePlaceRecognize(true).seg(text);
for (Term term : terms) {
if (term.nature.toString().startsWith("ns")) {
System.out.println("地名: " + term.word);
}
}
// 关键词提取
List<String> keywords = HanLP.extractKeyword(text, 3);
System.out.println("关键词: " + keywords);
}
}
输出:
分词结果: [清华大学/nt, 位于/v, 北京市/ns, 海淀区/ns, 。/w]
地名: 北京市
地名: 海淀区
关键词: [海淀区, 北京市, 清华大学]
6. 常见问题
- 词典加载失败:检查
hanlp.properties中的root路径是否正确。 - 内存不足:使用
portable版本或增加 JVM 内存:-Xms512m -Xmx1024m。 - 性能优化:对长文本使用
HanLP.segmentFaster()。
官方资源
HanLP 功能强大且灵活,适合中文 NLP 的各种场景!
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)