基于 Stanford CoreNLP 的中文自然语言处理
一、概述
Stanford CoreNLP 是斯坦福大学开发的一款强大的自然语言处理(NLP)工具,支持多种语言的文本处理,包括中文。本文将详细介绍如何使用 Stanford CoreNLP 实现中文文本的分词、词性标注、命名实体识别、句法分析等功能,并提供完整的代码示例和配置文件。
二、环境配置
1. Maven 依赖配置
在项目的 pom.xml
文件中添加以下依赖:
<dependencies><!-- Stanford CoreNLP --><dependency><groupId>edu.stanford.nlp</groupId><artifactId>stanford-corenlp</artifactId><version>${corenlp.version}</version></dependency><!-- Stanford CoreNLP Models --><dependency><groupId>edu.stanford.nlp</groupId><artifactId>stanford-corenlp</artifactId><version>${corenlp.version}</version><classifier>models</classifier></dependency><!-- Chinese Models --><dependency><groupId>edu.stanford.nlp</groupId><artifactId>stanford-corenlp</artifactId><version>${corenlp.version}</version><classifier>models-chinese</classifier></dependency>
</dependencies>
2. 配置文件
将以下配置文件保存为 CoreNLP-chinese.properties
,并放置在 src/main/resources
目录下:
# Pipeline options - lemma is no-op for Chinese but currently needed because coref demands it (bad old requirements system)
annotators = tokenize, ssplit, pos, lemma, ner, parse, coref# segment
tokenize.language = zh
segment.model = edu/stanford/nlp/models/segmenter/chinese/ctb.gz
segment.sighanCorporaDict = edu/stanford/nlp/models/segmenter/chinese
segment.serDictionary = edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz
segment.sighanPostProcessing = true# sentence split
ssplit.boundaryTokenRegex = [.\u3002]|[!?\uFF01\uFF1F]+# pos
pos.model = edu/stanford/nlp/models/pos-tagger/chinese-distsim.tagger# ner
ner.language = chinese
ner.model = edu/stanford/nlp/models/ner/chinese.misc.distsim.crf.ser.gz
ner.applyNumericClassifiers = true
ner.useSUTime = false# regexner
ner.fine.regexner.mapping = edu/stanford/nlp/models/kbp/chinese/gazetteers/cn_regexner_mapping.tab
ner.fine.regexner.noDefaultOverwriteLabels = CITY,COUNTRY,STATE_OR_PROVINCE# parse
parse.model = edu/stanford/nlp/models/srparser/chineseSR.ser.gz# depparse
depparse.model = edu/stanford/nlp/models/parser/nndep/UD_Chinese.gz
depparse.language = chinese# coref
coref.sieves = ChineseHeadMatch, ExactStringMatch, PreciseConstructs, StrictHeadMatch1, StrictHeadMatch2, StrictHeadMatch3, StrictHeadMatch4, PronounMatch
coref.input.type = raw
coref.postprocessing = true
coref.calculateFeatureImportance = false
coref.useConstituencyTree = true
coref.useSemantics = false
coref.algorithm = hybrid
coref.path.word2vec =
coref.language = zh
coref.defaultPronounAgreement = true
coref.zh.dict = edu/stanford/nlp/models/dcoref/zh-attributes.txt.gz
coref.print.md.log = false
coref.md.type = RULE
coref.md.liberalChineseMD = false# kbp
kbp.semgrex = edu/stanford/nlp/models/kbp/chinese/semgrex
kbp.tokensregex = edu/stanford/nlp/models/kbp/chinese/tokensregex
kbp.language = zh
kbp.model = none# entitylink
entitylink.wikidict = edu/stanford/nlp/models/kbp/chinese/wikidict_chinese.tsv.gz
三、代码实现
1. 初始化 Stanford CoreNLP 管道
创建 CoreNLPHel
类,用于初始化 Stanford CoreNLP 管道:
import edu.stanford.nlp.pipeline.StanfordCoreNLP;public class CoreNLPHel {private static CoreNLPHel instance = new CoreNLPHel();private StanfordCoreNLP pipeline;private CoreNLPHel() {String props = "CoreNLP-chinese.properties"; // 配置文件路径pipeline = new StanfordCoreNLP(props);}public static CoreNLPHel getInstance() {return instance;}public StanfordCoreNLP getPipeline() {return pipeline;}
}
2. 分词功能
创建 Segmentation
类,用于实现中文分词:
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;import java.util.List;public class Segmentation {private String segtext;public String getSegtext() {return segtext;}public Segmentation(String text) {CoreNLPHel coreNLPHel = CoreNLPHel.getInstance();StanfordCoreNLP pipeline = coreNLPHel.getPipeline();Annotation annotation = new Annotation(text);pipeline.annotate(annotation);List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);StringBuffer sb = new StringBuffer();for (CoreMap sentence : sentences) {for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {String word = token.get(CoreAnnotations.TextAnnotation.class);sb.append(word).append(" ");}}segtext = sb.toString().trim();}
}
3. 句子分割
创建 SenSplit
类,用于实现句子分割:
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;import java.util.ArrayList;
import java.util.List;public class SenSplit {private ArrayList<String> sensRes = new ArrayList<>();public ArrayList<String> getSensRes() {return sensRes;}public SenSplit(String text) {CoreNLPHel coreNLPHel = CoreNLPHel.getInstance();StanfordCoreNLP pipeline = coreNLPHel.getPipeline();Annotation annotation = new Annotation(text);pipeline.annotate(annotation);List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);for (CoreMap sentence : sentences) {sensRes.add(sentence.get(CoreAnnotations.TextAnnotation.class));}}
}
4. 词性标注
创建 PosTag
类,用于实现词性标注:
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;import java.util.List;public class PosTag {private String postext;public String getPostext() {return postext;}public PosTag(String text) {CoreNLPHel coreNLPHel = CoreNLPHel.getInstance();StanfordCoreNLP pipeline = coreNLPHel.getPipeline();Annotation annotation = new Annotation(text);pipeline.annotate(annotation);List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);StringBuffer sb = new StringBuffer();for (CoreMap sentence : sentences) {for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {String word = token.get(CoreAnnotations.TextAnnotation.class);String pos = token.get(CoreAnnotations.PartOfSpeechAnnotation.class);sb.append(word).append("/").append(pos).append(" ");}}postext = sb.toString().trim();}
}
5. 命名实体识别
创建 NamedEntity
类,用于实现命名实体识别:
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;import java.util.List;public class NamedEntity {private String nertext;public String getNertext() {return nertext;}public NamedEntity(String text) {CoreNLPHel coreNLPHel = CoreNLPHel.getInstance();StanfordCoreNLP pipeline = coreNLPHel.getPipeline();Annotation annotation = new Annotation(text);pipeline.annotate(annotation);List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);StringBuffer sb = new StringBuffer();for (CoreMap sentence : sentences) {for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {String word = token.get(CoreAnnotations.TextAnnotation.class);String ner = token.get(CoreAnnotations.NamedEntityTagAnnotation.class);sb.append(word).append("/").append(ner).append(" ");}}nertext = sb.toString().trim();}
}
6. 句法分析
创建 SPTree
类,用于实现句法分析:
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeCoreAnnotations;
import edu.stanford.nlp.util.CoreMap;import java.util.List;public class SPTree {private List<CoreMap> sentences;public SPTree(String text) {CoreNLPHel coreNLPHel = CoreNLPHel.getInstance();StanfordCoreNLP pipeline = coreNLPHel.getPipeline();Annotation annotation = new Annotation(text);pipeline.annotate(annotation);sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);}// 句子的依赖图(依存分析)public String getDepprasetext() {StringBuffer sb2 = new StringBuffer();for (CoreMap sentence : sentences) {String sentext = sentence.get(CoreAnnotations.TextAnnotation.class);SemanticGraph graph = sentence.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);sb2.append(sentext).append("\n");sb2.append(graph.toString(SemanticGraph.OutputFormat.LIST)).append("\n");}return sb2.toString().trim();}// 句子的解析树public String getPrasetext() {StringBuffer sb1 = new StringBuffer();for (CoreMap sentence : sentences) {Tree tree = sentence.get(TreeCoreAnnotations.TreeAnnotation.class);String sentext = sentence.get(CoreAnnotations.TextAnnotation.class);sb1.append(sentext).append("/").append(tree.toString()).append("\n");}return sb1.toString().trim();}
}
四、测试代码
1. 分词测试
public class Test {public static void main(String[] args) {System.out.println(new Segmentation("这家酒店很好,我很喜欢。").getSegtext());System.out.println(new Segmentation("他和我在学校里常打桌球。").getSegtext());System.out.println(new Segmentation("貌似实际用的不是这几篇。").getSegtext());System.out.println(new Segmentation("硕士研究生产。").getSegtext());System.out.println(new Segmentation("我是中国人。").getSegtext());}
}
2. 句子分割测试
public class Test1 {public static void main(String[] args) {String text = "巴拉克·奥巴马是美国总统。他在2008年当选?今年的美国总统是特朗普?普京的粉丝";ArrayList<String> sensRes = new SenSplit(text).getSensRes();for (String str : sensRes) {System.out.println(str);}}
}
3. 词性标注测试
public class Test2 {public static void main(String[] args) {String text = "巴拉克·奥巴马是美国总统。他在2008年当选?今年的美国总统是特朗普?普京的粉丝";System.out.println(new PosTag(text).getPostext());}
}
4. 命名实体识别测试
public class Test3 {public static void main(String[] args) {String text = "巴拉克·奥巴马是美国总统。他在2008年当选?今年的美国总统是特朗普?普京的粉丝";System.out.println(new NamedEntity(text).getNertext());}
}
5. 句法分析测试
public class Test4 {public static void main(String[] args) {String text = "巴拉克·奥巴马是美国总统。他在2008年当选?今年的美国总统是特朗普?普京的粉丝";SPTree spTree = new SPTree(text);System.out.println(spTree.getPrasetext());}
}
五、运行结果
1. 分词结果
这家 酒店 很好 , 我 很 喜欢 。
他 和 我 在 学校 里 常 打 桌球 。
貌似 实际 用 的 不 是 这几 篇 。
硕士 研究 生产 。
我 是 中国 人 。
2. 句子分割结果
巴拉克·奥巴马是美国总统。
他在2008年当选?
今年的美国总统是特朗普?
普京的粉丝
3. 词性标注结果
巴拉克·奥巴马/NNP 是/VC 美国/NNP 总统/NN 。/PU 他/PRP 在/IN 2008年/CD 当选/VBN ?/PU 今年/CD 的/POS 美国/NNP 总统/NN 是/VBP 特朗普/NNP ?/PU 普京/NNP 的/POS 粉丝/NN
4. 命名实体识别结果
巴拉克·奥巴马/PERSON 是/OTHER 美国/LOC 总统/OTHER 。/OTHER 他/OTHER 在/OTHER 2008年/DATE 当选/OTHER ?/OTHER 今年/DATE 的/OTHER 美国/LOC 总统/OTHER 是/OTHER 特朗普/PERSON ?/OTHER 普京/PERSON 的/OTHER 粉丝/OTHER
5. 句法分析结果
巴拉克·奥巴马是美国总统。/(ROOT(S(NP (NNP 巴拉克·奥巴马))(VP (VC 是)(NP (NNP 美国) (NN 总统)))(. 。)))
他在2008年当选?/(ROOT(S(NP (PRP 他))(VP (IN 在)(NP (CD 2008年))(VP (VBN 当选)))(? ?)))
今年的美国总统是特朗普?/(ROOT(S(NP (CD 今年) (DEG 的) (NNP 美国) (NN 总统))(VP (VBP 是)(NP (NNP 特朗普)))(? ?)))
普京的粉丝/ROOT(S(NP (NNP 普京) (DEG 的) (NN 粉丝)))
六、总结
本文详细介绍了如何使用 Stanford CoreNLP 实现中文文本的分词、句子分割、词性标注、命名实体识别和句法分析等功能。通过配置文件和代码实现,我们可以轻松地对中文文本进行处理和分析。这些功能在自然语言处理领域有广泛的应用,如文本分类、情感分析、机器翻译等。
相关文章:
基于 Stanford CoreNLP 的中文自然语言处理
一、概述 Stanford CoreNLP 是斯坦福大学开发的一款强大的自然语言处理(NLP)工具,支持多种语言的文本处理,包括中文。本文将详细介绍如何使用 Stanford CoreNLP 实现中文文本的分词、词性标注、命名实体识别、句法分析等功能&…...
python 量化交易入门到提升详细教程,python量化交易教程
文章目录 前言入门阶段1. 环境准备安装 Python选择开发环境安装必要的库 2. 金融数据获取3. 简单策略构建 - 移动平均线交叉策略 进阶阶段1. 策略回测2. 风险管理3. 多因子策略4. 机器学习在量化交易中的应用5. 高频交易策略 前言 Python 作为一门功能强大、易于学习且应用广泛…...
如何设置爬虫的访问频率?
设置爬虫的访问频率(即请求间隔)是确保爬虫稳定运行并避免对目标服务器造成过大压力的关键步骤。合理的访问频率不仅可以减少被目标网站封禁IP的风险,还能提高爬虫的效率。以下是一些设置爬虫访问频率的方法和最佳实践: 1. 使用s…...
前端循环全解析:JS/ES/TS 循环写法与实战示例
循环是编程中控制流程的核心工具。本文将详细介绍 JavaScript、ES6 及 TypeScript 中各种循环的写法、特性,并通过实际示例帮助你掌握它们的正确使用姿势。 目录 传统三剑客 for 循环 while 循环 do...while 循环 ES6 新特性 forEach for...of for...in 数组…...

大气体育直播模板赛事扁平自适应模板源码
源码名称:大气体育直播模板赛事网站源码 开发环境:帝国cms 7.5 安装环境:phpmysql 模板特点: 程序伪静态版本,实时采集更新,无人值守,省心省力。带火车头采集,可以挂着自动采集发布…...

vue3学习1
vite是新的官方构建工具,构建速度比webpack更快 vue项目的入口文件是index.html,一般在这里引入src/main.js,并且设置好容器#app App.vue放的是根组件,components里放分支组件 vue组件中写三种标签,template & s…...

java机器学习计算指标动态阈值
java机器学习计算指标动态阈值 最近听到有的人说要做机器学习就一定要学Python,我想他们掌握的知道还不够系统全面。本文作者以动态阈值需求场景给大家介绍几种常用Java实现的机器学习库,包括使用开源库如Weka或Deeplearning4j(DL4J…...
mac os设置jdk版本
打开环境变量配置文件 sudo vim ~/.bash_profile 设置不同的jdk版本路径 # 设置JAVA_HOME为jdk17路径 export JAVA_HOME$(/usr/libexec/java_home -v 17)# 设置JAVA_HOME为jdk8路径 export JAVA_HOME$(/usr/libexec/java_home -v 1.8) 设置环境变量 # 将jdk加入到环境变量…...
Python正则表达式学习
Python正则表达式全攻略 一、正则表达式基础 1. 什么是正则表达式? 用于描述字符串匹配规则的表达式广泛应用于文本处理、表单验证、数据清洗等领域 2. Python中的re模块 import re3. 基础语法 字符说明示例.匹配任意字符(除换行)a.c → abc\d数字 [0-9]\d\d …...
ShenNiusModularity项目源码学习(10:ShenNius.FileManagement项目分析)
ShenNiusModularity项目支持七牛云和本地图片存储,其文件上传接口及实现就位于ShenNius.FileManagement项目内,该项目内文件不多,主要就是围绕上传本地及七牛云的实现及相关类定义。 扩展类FileManagemenServiceExtensions的AddFileUploa…...

mysql查看binlog日志
mysql 配置、查看binlog日志: 示例为MySQL8.0 1、 检查binlog开启状态 SHOW VARIABLES LIKE ‘log_bin’; 如果未开启,修改配置my.ini 开启日志 安装目录配置my.ini(mysql8在data目录) log-binmysql-bin(开启日志并指定日志前缀ÿ…...
Node.js高频面试题精选及参考答案
目录 什么是 Node.js?它的主要特点有哪些? Node.js 的事件驱动和非阻塞 I/O 模型是如何工作的? 为什么 Node.js 适合处理高并发场景? Node.js 与传统后端语言(如 Java、Python)相比,有哪些优势和劣势? 简述 Node.js 的运行原理,包括 V8 引擎的作用。 什么是 Nod…...

TaskBuilder创建客户信息列表页面
3.4.1选择页面类型 点击上面创建的customer文件夹右侧的加号,打开“前端资源创建向导”对话框,选中“数据查询TFP”,资源名称会自动设置为index,这里我们不用改。 点“下一步”按钮,会弹出下图所示的“创建数据查询T…...
Linux Iptables示例一则
个人博客地址:Linux Iptables示例一则 | 一张假钞的真实世界 关于Iptables的介绍个人强烈推荐:iptables-朱双印博客-第2页。这位兄弟介绍的很详细。 我个人的需求是在同一个网络内从网络上把测试主机与正式环境主机间的网络进行隔离。我的思路是采用OU…...

新手小白如何挖掘cnvd通用漏洞之存储xss漏洞(利用xss钓鱼)
视频教程和更多福利在我主页简介或专栏里 (不懂都可以来问我 专栏找我哦) 如果对你有帮助你可以来专栏找我,我可以无偿分享给你对你更有帮助的一些经验和资料哦 目录: 一、XSS的三种类型: 二、XSS攻击的危害&#x…...
【CXX】4 跨平台构建系统特性对比
多语言构建系统选项为开发团队提供了灵活性和选择,以适应不同的项目需求和现有的技术栈。CXX作为一个设计灵活的工具,旨在与多种构建系统无缝集成。以下是对不同构建系统选项的简要概述和建议: 一、Cargo: 适用场景:…...
MySQL 如何使用EXPLAIN工具优化SQL
EXPLAIN 是 SQL 查询优化中的一个重要工具,主要用于分析和诊断查询执行计划。通过 EXPLAIN,我们可以了解数据库引擎(如 MySQL、PostgreSQL 等)是如何执行特定的查询语句的,包括是否使用了索引、表连接的方式、扫描的行…...

沃丰科技大模型标杆案例|周大福集团统一大模型智能服务中心建设实践
沃丰科技携手老客户周大福如何进行统一大模型智能服务中心建设 “我们相信,科技与创新是推动珠宝行业持续发展的关键力量。”——周大福珠宝集团董事总经理黄绍基。这句话再次强调了科技与创新在珠宝行业发展中的重要性&…...
代码随想录day16
513.找树左下角的值 //迭代法中左视图的最后一位 int findBottomLeftValue(TreeNode* root) {int result 0;queue<TreeNode*> qe;if(root nullptr) return result;qe.push(root);vector<int> lefts;while(!qe.empty()){int sz qe.size();vector<int> tmp…...
常见的软件测试模型及特点
软件测试模型有多种,常见的包括以下几种,每种模型都有其特点和适用场景: 1. V 模型(V-Model) 特点: 测试和开发并行进行,开发的每个阶段都有对应的测试活动。适用于需求明确、开发过程较规范的…...

接口测试中缓存处理策略
在接口测试中,缓存处理策略是一个关键环节,直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性,避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明: 一、缓存处理的核…...

AI-调查研究-01-正念冥想有用吗?对健康的影响及科学指南
点一下关注吧!!!非常感谢!!持续更新!!! 🚀 AI篇持续更新中!(长期更新) 目前2025年06月05日更新到: AI炼丹日志-28 - Aud…...
rknn优化教程(二)
文章目录 1. 前述2. 三方库的封装2.1 xrepo中的库2.2 xrepo之外的库2.2.1 opencv2.2.2 rknnrt2.2.3 spdlog 3. rknn_engine库 1. 前述 OK,开始写第二篇的内容了。这篇博客主要能写一下: 如何给一些三方库按照xmake方式进行封装,供调用如何按…...
多场景 OkHttpClient 管理器 - Android 网络通信解决方案
下面是一个完整的 Android 实现,展示如何创建和管理多个 OkHttpClient 实例,分别用于长连接、普通 HTTP 请求和文件下载场景。 <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas…...

渗透实战PortSwigger靶场-XSS Lab 14:大多数标签和属性被阻止
<script>标签被拦截 我们需要把全部可用的 tag 和 event 进行暴力破解 XSS cheat sheet: https://portswigger.net/web-security/cross-site-scripting/cheat-sheet 通过爆破发现body可以用 再把全部 events 放进去爆破 这些 event 全部可用 <body onres…...
Linux简单的操作
ls ls 查看当前目录 ll 查看详细内容 ls -a 查看所有的内容 ls --help 查看方法文档 pwd pwd 查看当前路径 cd cd 转路径 cd .. 转上一级路径 cd 名 转换路径 …...
鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院挂号小程序
一、开发准备 环境搭建: 安装DevEco Studio 3.0或更高版本配置HarmonyOS SDK申请开发者账号 项目创建: File > New > Create Project > Application (选择"Empty Ability") 二、核心功能实现 1. 医院科室展示 /…...
C++中string流知识详解和示例
一、概览与类体系 C 提供三种基于内存字符串的流,定义在 <sstream> 中: std::istringstream:输入流,从已有字符串中读取并解析。std::ostringstream:输出流,向内部缓冲区写入内容,最终取…...
OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别
OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...
动态 Web 开发技术入门篇
一、HTTP 协议核心 1.1 HTTP 基础 协议全称 :HyperText Transfer Protocol(超文本传输协议) 默认端口 :HTTP 使用 80 端口,HTTPS 使用 443 端口。 请求方法 : GET :用于获取资源,…...