使用Spacy实现命名实体识别
本次实验的目的是完成文本数据的词性标注和识别文本中的命名实体
一、数据来源
数据是2022年2月4日的新闻
二、数据预处理
使用jieba对文本进行分词和去停用词,使用的是哈工大的停用词表
import jieba
# 创建停用词列表 使用哈工大的停用词表
def stopwordslist():
stopwords = [line.strip() for line in open('hit_stopwords.txt',encoding='UTF-8').readlines()]
return stopwords
# 对句子进行中文分词
def seg_depart(sentence):
# 对文档中的每一行进行中文分词
sentence_depart = jieba.cut(sentence.strip())
# 创建一个停用词列表
stopwords = stopwordslist()
# 输出结果为outstr
outstr = ''
# 去停用词
for word in sentence_depart:
if word not in stopwords:
if word != '\t':
outstr += word
outstr += ""
return outstr
# 给出文档路径
filename = "data.txt"
outfilename = "out.txt"
inputs = open(filename, 'r', encoding='UTF-8')
outputs = open(outfilename, 'w', encoding='UTF-8')
# 将输出结果写入out.txt中
for line in inputs:
line_seg = seg_depart(line)
outputs.write(line_seg)
outputs.close() # 关闭文件
inputs.close()
print("删除停用词和分词成功!!!")
处理过后的数据
由于之后还要采用posseg进行分词,所以在预处理时并没有用“ ”(空格)将两个词分开。
三、使用posseg完成词性标注
导入第三方库
import jieba
import jieba.posseg as pseg
import paddle
text = ''
with open('out.txt','r',encoding='utf-8') as inf:
text = inf.read() # 读入文本数据
# print(text)
# 开启静态图模式
paddle.enable_static()
# # 引入paddle包,开启paddle模式
jieba.enable_paddle()
# 使用paddle分词,设置use_paddle=True
texts = pseg.cut(text,use_paddle = True)
# 存放人名
Person = []
# 存放地名
Location = []
# 存放机构名
Organization = []
# 存放时间
Time = []
for text,flag in texts:
if flag == 'PER':
Person.append(text)
if flag == 'LOC':
Location.append(text)
if flag == 'ORG':
Organization.append(text)
if flag == 'TIME':
Time.append(text)
print('%s %s'%(text,flag))
print("===========")
print("Person" + str(Person))
print("Location" + str(Location))
print("Organization" + str(Organization))
print("Time" + str(Time))
posseg 词性表
四、使用spacy实现命名实体可视化
import spacy
from spacy import displacy
from collections import Counter
nlp_zh = spacy.load('zh_core_web_sm') #加载中文包
def read_file(file_name): #打开要处理的文本
with open(file_name,'r',encoding='utf-8') as file:
return file.read()
text = read_file('out.txt') #读取文本
processed_text = nlp_zh(text)
# print(processed_text)
sentences = [s for s in processed_text.sents]
# print(len(sentences)) #输出有多少句话
displacy.render(processed_text,style='ent',jupyter=True)
def find_person(doc):
c = Counter()
for ent in processed_text.ents:
if ent.label_ == 'DATE':
c[ent.lemma_]+=1
return c.most_common(1)
print(find_person(processed_text))
查看spacy的版本号
!python -m spacy info
若是在按照中文包zh_core_web_sm出现错误时,需要检查中文包和spacy的版本是否一致。
查看词性表达的含义
spacy.explain("GPE")
spacy.explain("CARDINAL")
spacy.explain("EVENT")
spacy.explain("LOC")
源码程序
https://download.csdn.net/download/qq_45556665/86742175