《知识图谱从入门到实践》03 Python操作Neo4j
书山有路勤为径,学海无涯苦作舟1.建立Python连接需要Py2neo,通过该包,与Python建立连接这个包的版本需要在5以上,不然对应不了pip install py2neo==5.0b1建立连接需要以下代码from py2neo import Graphlink = Graph("http://localhost:7474",username="用户名",password="密码")2.数据
·
书山有路勤为径,学海无涯苦作舟
1.建立Python连接
需要Py2neo,通过该包,与Python建立连接
这个包的版本需要在5以上,不然对应不了
pip install py2neo==5.0b1
建立连接需要以下代码
from py2neo import Graph
link = Graph("http://localhost:7474",username="用户名",password="密码")
#高版本的用下面的
link = Graph("http://localhost:7474", auth=("neo4j", "112233"))
2.数据读取
可以先阅读下文档:https://py2neo.org/v4/index.html
取出来的数据需要构建称为一个字典,再将字典转换为一个dataframe
df_data的样子:
先提取数据中所需要的,将其构建成一个dataframe,从其提取出来需要构建节点和关系的数据,在将其节点和关系构建出来
# -*- coding: utf-8 -*-
from dataToNeo4jClass.DataToNeo4jClass import DataToNeo4j
import os
import pandas as pd
#pip install py2neo==5.0b1 注意版本,要不对应不了
invoice_data = pd.read_excel('./Invoice_data_Demo.xls', header=0, encoding='utf8')
#print(invoice_data)
def data_extraction():
"""节点数据抽取"""
#数据预处理,节点去重
# 取出购买方名称到list
node_buy_key = []
for i in range(0, len(invoice_data)):
node_buy_key.append(invoice_data['购买方名称'][i])
node_sell_key = []
for i in range(0, len(invoice_data)):
node_sell_key.append(invoice_data['销售方名称'][i])
# 去除重复的发票名称
node_buy_key = list(set(node_buy_key))
node_sell_key = list(set(node_sell_key))
# value抽出作node
node_list_value = []
for i in range(0, len(invoice_data)):
for n in range(1, len(invoice_data.columns)):
# 取出表头名称invoice_data.columns[i]
node_list_value.append(invoice_data[invoice_data.columns[n]][i])
# 去重
node_list_value = list(set(node_list_value))
# 将list中浮点及整数类型全部转成string类型
node_list_value = [str(i) for i in node_list_value]
return node_buy_key, node_sell_key,node_list_value
def relation_extraction():
"""联系数据抽取"""
links_dict = {}
sell_list = []
money_list = []
buy_list = []
#遍历取值,读取dataframe
for i in range(0, len(invoice_data)):
money_list.append(invoice_data[invoice_data.columns[19]][i])#金额,根据列表的位置读取数据所需要的数据,金额当作关系
sell_list.append(invoice_data[invoice_data.columns[10]][i])#销售方方名称
buy_list.append(invoice_data[invoice_data.columns[6]][i])#购买方名称
# 将数据中int类型全部转成string,这个是必须的,不然会报错。
sell_list = [str(i) for i in sell_list]
buy_list = [str(i) for i in buy_list]
money_list = [str(i) for i in money_list]
# 整合数据,将三个list整合成一个dict
links_dict['buy'] = buy_list
links_dict['money'] = money_list
links_dict['sell'] = sell_list
# 将数据转成DataFrame
df_data = pd.DataFrame(links_dict)
print(df_data)
return df_data
relation_extraction()
create_data = DataToNeo4j()
create_data.create_node(data_extraction()[0], data_extraction()[1])
create_data.create_relation(relation_extraction())
3.创建实体
先建立连接,必须先从cmd打开图数据库,才能建立连接。
# -*- coding: utf-8 -*-
from py2neo import Node, Graph, Relationship,NodeMatcher
class DataToNeo4j(object):
"""将excel中数据存入neo4j"""
def __init__(self):
"""建立连接"""
#link = Graph("http://localhost:7474", auth=("neo4j", "112233"))
link = Graph("http://localhost:7474", username="neo4j", password="112233")
self.graph = link
#self.graph = NodeMatcher(link)
# 定义label
self.buy = 'buy'
self.sell = 'sell'
self.graph.delete_all() #删除数据库中原有的节点,清空数据库
self.matcher = NodeMatcher(link)#匹配关系
"""
node3 = Node('animal' , name = 'cat')
node4 = Node('animal' , name = 'dog')
node2 = Node('Person' , name = 'Alice')
node1 = Node('Person' , name = 'Bob')
r1 = Relationship(node2 , 'know' , node1)
r2 = Relationship(node1 , 'know' , node3)
r3 = Relationship(node2 , 'has' , node3)
r4 = Relationship(node4 , 'has' , node2)
self.graph.create(node1)
self.graph.create(node2)
self.graph.create(node3)
self.graph.create(node4)
self.graph.create(r1)
self.graph.create(r2)
self.graph.create(r3)
self.graph.create(r4)
"""
def create_node(self, node_buy_key,node_sell_key):
"""建立节点"""
#去重后添加节点
for name in node_buy_key:
buy_node = Node(self.buy, name=name)
self.graph.create(buy_node)
for name in node_sell_key:
sell_node = Node(self.sell, name=name)
self.graph.create(sell_node)
def create_relation(self, df_data):
"""建立联系"""
m = 0
for m in range(0, len(df_data)):
try:
print(list(self.matcher.match(self.buy).where("_.name=" + "'" + df_data['buy'][m] + "'")))
print(list(self.matcher.match(self.sell).where("_.name=" + "'" + df_data['sell'][m] + "'")))
rel = Relationship(self.matcher.match(self.buy).where("_.name=" + "'" + df_data['buy'][m] + "'").first(),
df_data['money'][m], self.matcher.match(self.sell).where("_.name=" + "'" + df_data['sell'][m] + "'").first())
self.graph.create(rel)
except AttributeError as e:
print(e, m)

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)