gpt4 book ai didi

python - 将数据从 neo4j 导出到 csv 而不是 json

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:42 31 4
gpt4 key购买 nike

我正在使用 neo4jdb-python 包来查询 Neo4j 数据库。例如,考虑下面的代码

import neo4j
connection = neo4j.connect("http://localhost:7474")
cursor = connection.cursor()
for i in cursor.execute("MATCH a RETURN a LIMIT 1"):
print i

但是输出是元组的形式。即

({u'text': u'Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.', u'identifier': u'reference/lak/226'},)

如何获得 csv 格式的输出。这可以通过 neo4j 的 Web View 实现。输出就像,

"{""text"":""Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg."",""identifier"":""reference/lak/226""}"

但是我想通过客户端程序来完成,因为我需要将它嵌入到另一个程序中。如果 neo4jdb-python 无法实现,那么还有哪些其他选项可用。

最佳答案

Neo4j 服务器仅返回 JSON,正如 Mark Needham 在 his answer 中提到的那样.

因此,任何将其转换为 CSV 的代码都必须在客户端。这可以使用 csv 来完成模块。请注意,neo4jdb-python 包仅与 Python2.7 兼容。

获取数据的最小代码是

import neo4j
connection = neo4j.connect("http://localhost:7474")
cursor = connection.cursor()
data = list(cursor.execute("MATCH a RETURN a LIMIT 1")

请注意,如问题中所述,返回值采用元组形式。创建 csv 文件的最少代码是

with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile,delimiter = ',',quotechar = '"',quoting = csv.QUOTE_ALL)
writer.writerow(t[0].keys())
for i in t:
writer.writerow(['{"%s":"%s"}'%(k,v) for k,v in i.iteritems()])

代码解释很简单,打开一个文件。使用 csv.writer , 创建一个 writer 对象。首先使用 writerow 编写标题.最后遍历字典并写入行。

得到的输出是

"{""text"":""Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.""}","{""identifier"":""reference/lak/226""}"

这类似于使用 exportable.coffee 脚本获得的结果。

关于python - 将数据从 neo4j 导出到 csv 而不是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26816433/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com