文本命名实体提取并格式化

背景介绍

有一批不同分类的标题数据,每个标题中有不同的命名实体,需要提取每个分类的标题模板。所以,这里对标题进行命名实体提取并格式化处理形成标题模板数据。

实现代码

使用hanlp提取命名实体。

from pyhanlp import *
segment = HanLP.newSegment().enableOrganizationRecognize(True).enableNameRecognize(True);
print(segment)

#或者通过分词实现
NLPTokenizer = JClass("com.hankcs.hanlp.tokenizer.NLPTokenizer")
template = []
with open("/data/competition_title_5000.txt","r") as f:
    lines = f.read().split("\n")
    for line in lines:
        outstr = ""
        list = (NLPTokenizer.segment(line))
        for word in list:
            if word.nature.toString().startswith('nt'):
                outstr +='{org}'
            elif word.nature.toString().startswith('ns'):
                outstr +='{addr}'
            elif word.nature.toString().startswith('nr'):
                outstr += '{persons}'
            elif word.nature.toString().startswith('t'):
                outstr += '{date}'
            else:
                outstr += word.word
        print(outstr)
        template.append(outstr)

#将处理后的文本写入文件        
with open("/data/competition_template_5000.txt","w") as f:
    i = 0
    for t in template:
        i = i + 1
        message = "%s|%s|%s\n"%(i,len(t),t)
        f.write(message)
        print(message)

总结

这里使用hanlp方式提取命名实体。也可以使用百度NLP,这两种是我们优选出来的命名实体提取框架,同时百度NLP应用效果稍好一些,支持自定义增加命名实体。近期,腾讯的NER命名实体提取框架也出来了,后期会分享一篇这三者NER效果对比。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。