栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

neo4j+python(2)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

neo4j+python(2)

导入csv文件

文件位置
–PyNeo
-----data
--------math.csv
-----run.py

代码

# -*- coding:utf-8 -*-
# 读取csv文件的三元组

import os
import csv
import codecs
from py2neo import Node,Relationship,Graph,NodeMatcher

data_path = "./data"
file_name = 'math.csv'
file = os.path.join(data_path, file_name)

def load_csv(file):
    data_list = []
    with codecs.open(file, encoding='ANSI') as f:
        reader = csv.DictReader(f)
        for line in reader:
            data = list(line.values())
            data_list.append(data)
        return data_list

tri_list = load_csv(file) # [ [head,relation,tail],[head,relation,tail],[head,relation,tail]...]

head_entities = []
relations = []
tail_entities = []

for s in tri_list:
    head_entities.append(s[0])
    relations.append(s[1])
    tail_entities.append(s[2])

graph = Graph('http://localhost:7474', username='neo4j', password='0208')
graph.delete_all()
matcher = NodeMatcher(graph)

entities = set(head_entities + tail_entities)
for n in entities:
    graph.create(Node('Concept', name = n))  # 创建所有实体节点

for i in range(len(relations)):
    head = head_entities[i]
    head_node = matcher.match('Concept').where("_.name="+"'"+head+"'").first() #去掉重复节点

    tail = tail_entities[i]
    tail_node = matcher.match('Concept').where("_.name="+"'"+tail+"'").first()

    relation = relations[i]
    graph.create(Relationship(head_node, relation, tail_node))  #创建关系

最大收获:

head_node = matcher.match('Concept').where("_.name="+"'"+head+"'").first()

可以去掉重复节点,参考:https://blog.csdn.net/zsh1184528359/article/details/106003346/

其他注意事项写在前一篇了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938718.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号