利用python构建知识图谱,报错语法错误,具体信息如下,代码能够运行,但是neo4j中没有出现关系,只出现了节点
具体报错信息如下:
```python
SyntaxError: Invalid input '2': expected whitespace, '.', node labels or rel types, '[', '^', '*', '/', '%', '+', '-', "=~", IN, STARTS, ENDS, CONTAINS, IS, '=', "<>", "!=", '<', '>', "<=", ">=", AND, XOR, OR, USE GRAPH, LOAD CSV, START, MATCH, UNWIND, MERGE, CREATE UNIQUE, CREATE, SET, DELETE, REMOVE, FOREACH, WITH, CALL, RETURN, UNION, ';' or end of input (line 1, column 45 (offset: 44))
"match(p:author),(q:article) where p.name='['2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年']'and q.name='2014年' create (p)-[rel:first_author{name:'第一作者'}]->(q)"
```下面是构建关系的代码
def create_graphrels(self):
author, article, rels_writer = self.read_nodes()
self.create_relationship('author', 'article', rels_writer, 'first_author', '第一作者')
'''创建实体关联边'''
def create_relationship(self, start_node, end_node, edges, rel_type, rel_name):
count = 0
# 去重处理
set_edges = []
for edge in edges:
set_edges.append('###'.join(map(str,edge)))
all = len(set(set_edges))
for edge in set(set_edges):
edge = edge.split('###')
p = edge[0]
q = edge[1]
query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
start_node, end_node, p, q, rel_type, rel_name)
try:
self.g.run(query)
count += 1
print(rel_type, count, all)
except Exception as e:
print(e)
return
“Devil组”引证GPT后的撰写:
根据报错信息,可以看出问题出现在这行代码中:
"match(p:author),(q:article) where p.name='['2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年', '2014年']'and q.name='2014年' create (p)-[rel:first_author{name:'第一作者'}]->(q)"
具体问题在于,字符串中的 p.name 参数值使用了引号包含一个列表,但是这是不正确的语法,应该将引号替换为双引号或不使用引号,具体替换如下:
query = 'match(p:%s),(q:%s) where p.name=["%s"] and q.name="%s" create (p)-[rel:%s{name:"%s"}]->(q)' % (
start_node, end_node, p, q, rel_type, rel_name)
或者使用 Python 的 f-string 格式化字符串:
query = f'match(p:{start_node}),(q:{end_node}) where p.name=["{p}"] and q.name="{q}" create (p)-[rel:{rel_type}{{name:"{rel_name}"}}]->(q)'
这应该会解决你的问题
query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
start_node, end_node, p, q, rel_type, rel_name)
中引用的p是列表,里面各元素间用单引号包裹,而引用时外层也是单引号,造成引号匹配出错了,可修改如下:
query = "match(p:%s),(q:%s) where p.name=\"%s\" and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
start_node, end_node, p, q, rel_type, rel_name)
# 或者不用引号
query = "match(p:%s),(q:%s) where p.name = %s and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
start_node, end_node, p, q, rel_type, rel_name)