python中使用StanfordCoreNLP,进行命名实体识别

本文在Python中使用StanfordOpenIE已经抽取出(实体,关系,实体)的基础之上,进行时间实体的抽取。(本文参考了python中stanfordCorenlp使用教程博文,感谢这位博主的分享!)
结果如下:
在这里插入图片描述

1、安装 StanfordCoreNLP :pip install stanfordcorenlp

  • 查看是否安装成功:pip list
    在这里插入图片描述
    2、代码实现:
from stanfordcorenlp import StanfordCoreNLP
from tqdm import trange
import os

def Corenlp(infile,outfile):
    nlp = StanfordCoreNLP(r'E:\NLP_Tools\StanfordNLP\.stanfordnlp_resources\stanford-corenlp-4.1.0')
    datefile = open(outfile,'w',encoding='utf-8')
    date_List = ['DATE','TIME']         #时间类实体列表
    with open(infile,'r',encoding='utf-8') as f:
        line = f.readline()         #读取第一行
        while line:
            dict_triple = eval(line)                #将字符串转为字典:{'subject': 'Vagococcus silagei', 'relation': 'is non-spore-forming bacterium from', 'object': 'genus'}
            str_triple1 = dict_triple['subject']
            str_triple2 = dict_triple['object']
            len_str_triple1 = len(nlp.ner(str_triple1))         #获取字符串中有多少个单词
            len_str_triple2 = len(nlp.ner(str_triple2))
            for idx1 in range(len_str_triple1):          #[('Vagococcus', 'O'), ('silagei', 'O')]   ----->  列表形式是:[(单词,标注)]
                if nlp.ner(str_triple1)[idx1][1] in date_List:
                    datefile.write(line)            #写入文本的是字符串
                    print(line)
                    break
            for idx2 in range(len_str_triple2):
                if nlp.ner(str_triple2)[idx2][1] in date_List:
                    datefile.write(line)            #最好判断一下line是否已经写入文本中
                    print(line)
                    break
            line = f.readline()        #读取文本下一行
    nlp.close()         #要关闭
    datefile.close()

infile = os.path.join('../Data/enwiki/result','res_wiki_en.txt')
outfile = os.path.join('../Data/enwiki/result','res_date_en.txt')
Corenlp(infile,outfile)

注:

  • 为了读取文本时,防止内存爆满,则使用一行一行读取形式:readline()
  • nlp使用结束:nlp close()
  • 文本中存放的是字符串,要转为字典:eval()
  • 将数据写入文本时,要以字符串的形式
  • 对于在(实体,关系,实体)的三元组中抽取时间实体,主要用到的就是nlp.ner(str)函数,对一个句子中实体进行分类,本文需要的是’DATE、TIME’。
  • 其他实体分类:
3 class: Location, Person, Organization
4 class: Location, Person, Organization, Misc
7 class: Location, Person, Organization, Money, Percent, Date, Time

这是小新学习的小记录,有不对的地方希望UU们批评指正
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值