(头实体,关系,尾实体)
(头实体,关系,尾实体)
。。。。。。
在执行python代码之前在neo4j中执行这个命令,清空所有节点
match (n) detach delete n
import py2neo
from py2neo import Graph,Node,Relationship,NodeMatcher
import csv
graph = Graph('http://localhost:7474',user='neo4j',password='自己的密码,neo4j的初始密码是neo4j')
# 打开txt文件
with open("数据文件路径", "r", encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
# 分割每行数据
triple = line.strip().split(", ")
triple[0] = triple[0].replace("(", "")
triple[2] = triple[2].replace(")", "")
# 创建节点和关系
head_node = Node("Entity", name=triple[0], primary_label="Entity", primary_key="name")
tail_node = Node("Entity", name=triple[2], primary_label="Entity", primary_key="name")
relationship = Relationship(head_node, triple[1], tail_node)
graph.merge(head_node, "Entity", "name")
graph.merge(tail_node, "Entity", "name")
graph.merge(relationship)
#关闭连接 这行代码会报错,AttributeError: 'Graph' object has no attribute 'close'
# 是为了看什么时候导入完成,报错的时候说明前面的执行完了,就导入完成了
graph.close()
头实体 | 关系 | 尾实体 |
---|---|---|
头实体 | 关系 | 尾实体 |
with open("数据文件路径", "r", encoding='utf-8') as f:
reader = csv.reader(f)
for item in reader:
head_node = Node("Entity", name=item[0], primary_label="Entity", primary_key="name")
tail_node = Node("Entity", name=item[2], primary_label="Entity", primary_key="name")
relationship = Relationship(head_node, item[1], tail_node)
graph.merge(head_node, "Entity", "name")
graph.merge(tail_node, "Entity", "name")
graph.merge(relationship)
#关闭连接
graph.close()