基于 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) 特点: 测试和开发并行进行,开发的每个阶段都有对应的测试活动。适用于需求明确、开发过程较规范的…...
IDEA运行Tomcat出现乱码问题解决汇总
最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…...
Flask RESTful 示例
目录 1. 环境准备2. 安装依赖3. 修改main.py4. 运行应用5. API使用示例获取所有任务获取单个任务创建新任务更新任务删除任务 中文乱码问题: 下面创建一个简单的Flask RESTful API示例。首先,我们需要创建环境,安装必要的依赖,然后…...
Module Federation 和 Native Federation 的比较
前言 Module Federation 是 Webpack 5 引入的微前端架构方案,允许不同独立构建的应用在运行时动态共享模块。 Native Federation 是 Angular 官方基于 Module Federation 理念实现的专为 Angular 优化的微前端方案。 概念解析 Module Federation (模块联邦) Modul…...
ElasticSearch搜索引擎之倒排索引及其底层算法
文章目录 一、搜索引擎1、什么是搜索引擎?2、搜索引擎的分类3、常用的搜索引擎4、搜索引擎的特点二、倒排索引1、简介2、为什么倒排索引不用B+树1.创建时间长,文件大。2.其次,树深,IO次数可怕。3.索引可能会失效。4.精准度差。三. 倒排索引四、算法1、Term Index的算法2、 …...
用机器学习破解新能源领域的“弃风”难题
音乐发烧友深有体会,玩音乐的本质就是玩电网。火电声音偏暖,水电偏冷,风电偏空旷。至于太阳能发的电,则略显朦胧和单薄。 不知你是否有感觉,近两年家里的音响声音越来越冷,听起来越来越单薄? —…...
虚拟电厂发展三大趋势:市场化、技术主导、车网互联
市场化:从政策驱动到多元盈利 政策全面赋能 2025年4月,国家发改委、能源局发布《关于加快推进虚拟电厂发展的指导意见》,首次明确虚拟电厂为“独立市场主体”,提出硬性目标:2027年全国调节能力≥2000万千瓦࿰…...
代码规范和架构【立芯理论一】(2025.06.08)
1、代码规范的目标 代码简洁精炼、美观,可持续性好高效率高复用,可移植性好高内聚,低耦合没有冗余规范性,代码有规可循,可以看出自己当时的思考过程特殊排版,特殊语法,特殊指令,必须…...
华为OD机试-最短木板长度-二分法(A卷,100分)
此题是一个最大化最小值的典型例题, 因为搜索范围是有界的,上界最大木板长度补充的全部木料长度,下界最小木板长度; 即left0,right10^6; 我们可以设置一个候选值x(mid),将木板的长度全部都补充到x,如果成功…...
Oracle11g安装包
Oracle 11g安装包 适用于windows系统,64位 下载路径 oracle 11g 安装包...
规则与人性的天平——由高考迟到事件引发的思考
当那位身着校服的考生在考场关闭1分钟后狂奔而至,他涨红的脸上写满绝望。铁门内秒针划过的弧度,成为改变人生的残酷抛物线。家长声嘶力竭的哀求与考务人员机械的"这是规定",构成当代中国教育最尖锐的隐喻。 一、刚性规则的必要性 …...
