Bha*_*Rao 3 python csv list neo4j cypher
我正在使用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视图实现.输出就像,
"{""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在他的回答中提到的那样.
因此,任何将其转换为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脚本获得的类似.
| 归档时间: | 
 | 
| 查看次数: | 1559 次 | 
| 最近记录: |