项目场景:
前面两步,我们已经把所有的前期准备都已经完成,最后我们回归步骤一的本源,沉积学知识图谱的补充和扩建,我识别出文本内关键信息实体,提取到实体见的关系,那我就可以对知识图谱进行反向补充,这样就实现了学术界human in the loop的方案。
知识图谱的补充
这里首先我们先要连接本地的知识图谱库
__author__ = "Huzhichen"
#coding=utf-8
import json
from py2neo import Graph, Node, Relationship, cypher, NodeMatcher, RelationshipMatcher
graph = Graph("http://localhost:7474", auth=("neo4j", "admin"))
这里我举个例子,之后所有的数据填充可根据自己提取的数据自行补充,这里只展现关键的代码,第一步创建节点,在创建前我们要先进行查找如果没有才能创建,如果有就不创建,.replace(" “,”")).where(".name="+"’"+long[index]+"’").exists()这里为Neo4j 3,py2neio为2021版本,这也是目前固定写法,照抄里面数组就行
matcher = NodeMatcher(graph)
# 测试及查询创建实体节点
has = ['Limestone','Clasts']
long = ['clasts','micritic limestone','pink pelagic limestone']
# 创建节点
for index in range(len(long)):
if matcher.match(long[index].replace(" ","_")).where("_.name="+"\'"+long[index]+"\'").exists() == False:
loc_node= Node(long[index].replace(" ","_"),label=long[index].replace(" ","_"),name=long[index])
graph.create(loc_node)
print(long[index]+"节点不存在正在创建")
else:
loc_node=matcher.match(long[index].replace(" ","_")).where("_.name="+"\'"+long[index]+"\'").first()
print(long[index]+"节点已经存在")
for index in range(len(has)):
if matcher.match(has[index].replace(" ","_")).where("_.name="+"\'"+has[index]+"\'").exists() == False:
has_node= Node(has[index].replace(" ","_"),label=has[index].replace(" ","_"),name=has[index])
graph.create(has_node)
print(has[index]+"节点不存在正在创建")
else:
has_node=matcher.match(has[index].replace(" ","_")).where("_.name="+"\'"+has[index]+"\'").first()
print(has[index]+"节点已经存在")
最后创建关系,这里的关系,在数据导入Neo4j之前,已经做好了分类,肯定是前面两个关系相同的数组导入在导入关系。
# 创建节点之间的连接
for index in range(len(long)):
for hasindex in range(len(has)):
if (long[index].lower().find(has[hasindex].lower()) != -1):
loc_node = matcher.match(long[index].replace(" ", "_")).where("_.name=" + "\'" + long[index] + "\'").first()
has_node = matcher.match(has[hasindex].replace(" ", "_")).where("_.name=" + "\'" + has[hasindex] + "\'").first()
relationshipLevel = Relationship(has_node, 'subclass', loc_node)
graph.create(relationshipLevel)
print("关键创建成功")
效果图如下
目前节点:2614 关系:2613 数量:600篇文献
GitHub代码如下:https://github.com/zhichen-roger/Relationship_extraction_and_knowledge-graph-supplementation.git
如果对你的文章有帮助请引用目前发表的文章