编程语言
首页 > 编程语言> > 命名体识别 python Stanford CoreNLP

命名体识别 python Stanford CoreNLP

作者:互联网

简介

StanfordCoreNLP 是斯坦福大学发布的 NLP 处理工具,StanfordCoreNLP 的源码使用 Java 编写,目前 Python 可以用两种方法进行调用,一种是使用 StanfordCoreNLP 库,是对 StanfordCoreNLP 进行了 Python 封装。而另一种方法是直接使用 Stanford 官方发布的 Python 版本 StanfordNLP。这里介绍第一种方式。

Stanford CoreNLP安装方法

(1)下载stanford CoreNLP 相关文件,需下载两个文件,相关语言的 JAR 模型,以及 CoreNLP (https://stanfordnlp.github.io/CoreNLP/
在这里插入图片描述

(2)解压下载好的 CoreNLP 文件,并将 JAR 模型放在加压好的文件夹中

mv /path/to/stanford-corenlp-***.jar /path/to/stanford-corenlp-***

(3)python3中安装stanfordcorenlp

pip install stanfordcorenlp 

以上就完成了安装准备工作,可以开始使用 StanfordCoreNLP 来进行分词,词性标注,命名实体识别等工作了。

在安装的过程中,由于下载的CoreNLP文件和pip install的版本不一致,报错 psutil.AccessDenied: psutil.AccessDenied (pid=22147),版本一致后错误解决

使用

1 命名体识别

#encoding="utf-8"
from stanfordcorenlp import StanfordCoreNLP
import os

if os.path.exists('D:\\stanford_nlp\\stanford-corenlp-full-2018-10-05'):
    print("corenlp exists")
else:
    print("corenlp not exists")
nlp=StanfordCoreNLP('D:\\stanford_nlp\\stanford-corenlp-full-2018-10-05',lang='zh')
sentence = '王明是清华大学的一个研究生'
#print (nlp.word_tokenize(sentence))   #分词
#print (nlp.pos_tag(sentence))     #词性
print (nlp.ner(sentence))   #NER

#print (nlp.parse(sentence))     #语法分析
#print (nlp.dependency_parse(sentence))   #语法依赖关系

[(‘王明’, ‘PERSON’), (‘是’, ‘O’), (‘清华’, ‘ORGANIZATION’), (‘大学’, ‘ORGANIZATION’), (‘的’, ‘O’), (‘一’, ‘NUMBER’), (‘个’, ‘O’), (‘研究生’, ‘O’)]
2 将实体连接在一起

res = nlp.ner(sentence)
tag = 0
name = ''
labels = []
for i in range(len(res)):
    if res[i][1] != 'ORGANIZATION':
        if tag != 0:
            labels.append(name)
            name = ''
            tag = 0
    else:
        tag = 1
        name += res[i][0]

print(res)
print(labels)

参考文档:
原文链接:https://blog.csdn.net/ZJRN1027/article/details/103513861
https://cloud.tencent.com/developer/article/1387652

标签:nlp,sentence,python,Stanford,stanford,print,CoreNLP,StanfordCoreNLP
来源: https://blog.csdn.net/subian1261/article/details/114820006