py2neo创建知识图谱
效果展示

数据
1. data.csv
| index |
person |
canteen |
address |
fond |
| 1 |
Peanut |
四食堂 |
南京 |
学习 |
| 2 |
皮卡丘 |
五食堂 |
徐州 |
玩游戏 |
| 3 |
曹操 |
七食堂 |
山西 |
打羽毛球 |
| 4 |
刘备 |
二食堂 |
湖北 |
乒乓球 |
| 5 |
憨憨 |
一食堂 |
北京 |
吃鱼 |
2. person.csv
| 序号 |
姓名 |
关系 |
姓名 |
| 1 |
Peanut |
哥哥 |
皮卡丘 |
| 2 |
Peanut |
主公 |
曹操 |
| 3 |
Peanut |
弟弟 |
刘备 |
| 4 |
Peanut |
好盆友 |
憨憨 |
| 5 |
皮卡丘 |
好盆友 |
憨憨 |
3. adress.csv
| 序号 |
地点 |
关系 |
地点 |
| 1 |
南京 |
同省 |
徐州 |
| 2 |
南京 |
南边 |
北京 |
4. canteen.csv
| 序号 |
地点 |
关系 |
地点 |
| 1 |
南京 |
同省 |
徐州 |
| 2 |
南京 |
南边 |
北京 |
5. fond.csv
| 序号 |
fond |
关系 |
fond |
| 1 |
吃鱼 |
没有它的运动效果好 |
打羽毛球 |
| 2 |
学习 |
耗费脑力 |
吃鱼 |
| 3 |
乒乓球 |
运动量大 |
吃鱼 |
代码
from py2neo import Graph, Node, Relationship
from py2neo.matching import NodeMatcher
import pathlib2 as plb2
import pandas as pd
graph = Graph("bolt://192.168.136.55:7687",auth=('neo4j','123456'))
nodes = NodeMatcher(graph)
graph.delete_all() #清除neo4j中原有的结点等所有信息
def create_node(url,graph=graph):
#csv格式:第一列:序号
df = pd.read_csv(url)
ontolist = df.columns.to_numpy()
#print(ontolist)
#创建节点
for index in df.index:
row = df.loc[index].values[1:]
for i in range(len(row)):
node = Node(ontolist[i+1],name=row[i])
graph.create(node)
#创建关系
for index in df.index:
row1 = df.loc[index].values[1:]
for i in range(len(ontolist)-2):
relation = Relationship(nodes.match(ontolist[1],name=row1[0]).first(),ontolist[i+2],nodes.match(ontolist[i+2],name=row1[i+1]).first())
graph.create(relation)
def create_relationship(url,attribute,graph=graph):
#csv格式:第一列:序号,第二列:属性一;第三列:关系,第四列:属性二
df = pd.read_csv(url)
for index in df.index:
row = df.loc[index].values[1:]
relation = Relationship(nodes.match(attribute,name=row[0]).first(),row[1],nodes.match(attribute,name=row[2]).first())
graph.create(relation)
#创建节点
url_node = 'data.csv'
create_node(url_node)
#创建关系
url_relation = './data'
filelist = [file for file in plb2.Path(url_relation).glob('*.csv')]
filelist.sort(reverse=False)
for i in range(len(filelist)):
relation = str(filelist[i]).split('\\')[1].split('.')[0]
create_relationship(filelist[i],relation)