Graph类:
#Import dependencies
from py2neo import Graph, Node, Relationship
import json
# 连接数据库
# 测试用数据
Map1 = {'label':'小黑','introduce':'小黑就是这么的无敌,未来的NLP算法工程师','age':'22','class':'People'}
Map2 = {'label':'黄忠','introduce':'跟随小黑的步伐一起美白,走向人生巅峰','age':'23','class':'People'}
Map3 = {'label':'程咬金','introduce':'打过电赛的学霸一枚,经常使用"我不!!"来拒绝别人','age':'23','class':'People'}
Maps = [Map1,Map2,Map3]
relates = [{'obj':'小黑','pre':'朋友','sub':'黄忠','domain':'People','range':'People'},
{'obj':'小黑','pre':'朋友','sub':'程咬金','domain':'People','range':'People'},
{'obj':'黄忠','pre':'朋友','sub':'小黑','domain':'People','range':'People'},
{'obj':'黄忠','pre':'朋友','sub':'程咬金','domain':'People','range':'People'},
{'obj':'程咬金','pre':'朋友','sub':'黄忠','domain':'People','range':'People'},
{'obj':'程咬金','pre':'朋友','sub':'小黑','domain':'People','range':'People'},
{'obj':'程咬金','pre':'同门','sub':'黄忠','domain':'People','range':'People'},
{'obj':'黄忠','pre':'同门','sub':'程咬金','domain':'People','range':'People'}]
class Graph_Neo4j(object):
def __init__(self):
self.graph = self.connect_neo4j()
self.rest = []
def write_items(self,items, name):
js = json.dumps(items)
file = open(name + '.txt', 'w')
file.write(js)
file.close()
def connect_neo4j(self):
graph = Graph(
"http://localhost:7474",
username="neo4j",
password="xiaoheidiyi123"
)
return graph
# 创建实体(class,Map)
def create_entity(self, Map):
if 'label' not in Map and 'class' not in Map:
print('没有label或class!!创建失败')
return None
Class = Map['class']
a = Node(Class,name = Map['label'],label = Map['label'])
for key in Map:
if key != 'class':
a[key] = Map[key]
self.graph.create(a)
return a
def create_entities(self,Maps):
for t,Map in enumerate(Maps):
try:
node = self.create_entity(Map)
if node:
print('第',t,'个实体创建成功')
else:
print('第',t,'个\n',Map,'创建失败')
except:
print('第', t, '个实体创建成功')
# 获取实体(class,pre,value)
def get_entity(self,Class, pre, value):
node = self.graph.run('MATCH (n:' + Class + ') where n.' + pre + '="' + value + '" RETURN n').data()
if len(node):
return node[0]['n']
else:
return None
def get_name_entity(self,Class, label):
return self.get_entity(Class, 'label', label)
# 添加属性
def add_property(self,node, key, value):
node.update({key: value})
self.graph.push(node)
return node
# 添加关系
def add_relate(self,obj, pre, sub):
if obj and sub:
r = Relationship(obj, pre, sub)
return r
else:
return None
def create_retales(self,relates):
rest = []
for t, relate in enumerate(relates):
try:
obj = relate['obj']
pre = relate['pre']
sub = relate['sub']
domain = relate['domain']
Range = relate['range']
node1 = self.get_name_entity(domain, obj)
node2 = self.get_name_entity(Range, sub)
if node1 and node2:
r = self.add_relate(node1, pre, node2)
self.graph.create(r)
print(t, '个关联成功')
else:
print((obj, pre, sub), '关联失败!!')
rest.append(relate)
except:
print((obj, pre, sub), '关联失败!!')
rest.append(relate)
if rest:
self.write_items(rest,'未关联关系')
self.rest = rest
return rest
# 统计实体关系以及三元组个数
def statistics(self):
class_num = self.graph.run('CALL db.labels() YIELD label return size(collect(label))').data()[0][
'size(collect(label))']
entity_num = self.graph.run('MATCH (n) RETURN count(n)').data()[0]['count(n)']
relate_num = self.graph.run('match (n)-[r]->() return count(r)').data()[0]['count(r)']
print('实体类型总数:', class_num, '\n实体总数:', entity_num, '\n关系总数:', relate_num)
if __name__ == '__main__':
g = Graph_Neo4j()
g.statistics()
调用代码:
import re
import json
from Graph import Graph_Neo4j
def write_items(items,name):
js = json.dumps(items)
file = open(name+'.txt', 'w')
file.write(js)
file.close()
def load_items(name):
file = open(name+'.txt', 'r')
js = file.read()
items = json.loads(js)
return items
#Maps = load_items('./data/实体属性')
#relates = load_items('./data/实体关系')
g = Graph_Neo4j()
#g.create_entities(Maps)
#g.create_retales(relates)
#g.statistics()
#print('未关联关系个数:', len(g.rest))
# 剩余实体的关联
g.statistics()
#-----------------------------------------------未关联实体操作----------------------------------------
"""
rest = load_items('未关联关系')
for t,item in enumerate(rest):
obj = item['obj']
pre = item['pre']
sub = item['sub']
domain = item['domain']
Range = item['range']
#node1 = g.get_name_entity(domain, obj)
#node2 = g.get_name_entity(Range, sub)
#print(node1,node2)
if Range == '糖、蜜饯类' or Range == '小吃、甜饼' :
node1 = g.graph.run('MATCH (n:' + domain + ') where n.label="' + obj + '" RETURN n').data()[0]['n']
node2 = g.graph.run('MATCH (n) where n.label = "'+sub+'" RETURN n').data()[0]['n']
r = g.add_relate(node1, pre, node2)
g.graph.create(r)
print(t)
"""