我有一个用例,从SPARQL端点提取数据,如下所示:
SPARQL = SPARQLWrapper(endpointURL)
SPARQL.setQuery(queryString)
SPARQL.setReturnFormat(JSON)
results = SPARQL.query().convert()
“results”变量保存我现在要写入CSV文件的数据。首先,我为CSV创建了标题,如下所示:
schema = ['Age', 'Sex', 'Chest_Pain_Type', 'Trestbps', 'Chol', 'Fasting_Glucose_Level', 'Resting_ECG_Type', 'ThalachD', 'Exercise_Induced_Angina', 'OldpeakD', 'CaD', 'Slope', 'Thallium_Scintigraphy', 'Diagnosis']
然后,我使用以下代码将每一行的数据写入CSV文件:
with open('DIC.csv', 'w+') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerow([g for g in schema])
for result in results["results"]["bindings"]:
writer.writerow([result["Age"]["value"],
result["SexTypes"]["value"],
result["Chest_Pain_Type"]["value"],
result["trestbpsD"]["value"],
result["cholD"]["value"],
result["Fasting_Glucose_Level"]["value"],
result["Resting_ECG_Type"]["value"],
result["thalachD"]["value"],
result["Exercise_Induced_Angina"]["value"],
result["oldpeakD"]["value"],
result["caD"]["value"],
result["Slope"]["value"],
result["Thallium_Scintigraphy"]["value"],
result["Diagnosis"]["value"]])
file_name = csvfile.name
csvfile.close()
在前面的代码块中,result[“SexTypes”][“value”]用于写入列“SexTypes”的值(即“value”)。也就是说,第一个索引是可变的,但是第二个索引总是相同的。你知道吗
尽管上面的代码工作得很好,但这是非常硬的编码,一旦SPARQL查询发生更改(即,如果模式不同),就会失败。你知道吗
我现在想让它更灵活,这样我可以迭代列表中的所有列,但是“值”是固定的。为此,我尝试了以下代码,但最终失败:
with open('DIC.csv', 'w+') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerow([g for g in schema])
r = "value"
for result in results["results"]["bindings"]:
for i in range(len(schema)):
writer.writerow([result[schema[i]][r]])
i = i + 1
file_name = csvfile.name
csvfile.close()
return file_name
我知道,我做错了什么。有更好的建议吗?你知道吗
[也许这个问题应该有一个更好的标题,但我找不到任何。对不起,我的英语不好
在第一个示例代码中,
writer.writerow()
的输入是一个列表,其长度与schema
相同,而在第二个示例代码中,它是一个长度为1的列表(而不是调用writerow()
,而是调用schema
中的每个元素一次)。你知道吗要首先生成列表,可以使用列表理解:
相当于:
最终,只需在
results
上的循环内修改代码:相关问题 更多 >
编程相关推荐