从 Google Colab 的结果创建 CSV
我正在使用维基数据查询服务来获取值,这是代码:
pip install sparqlwrapper
import sys
from SPARQLWrapper import SPARQLWrapper, JSON
endpoint_url = "https://query.wikidata.org/sparql"
query = """#List of organizations
SELECT ?org ?orgLabel
WHERE
{
?org wdt:P31 wd:Q4830453. #instance of organizations
?org wdt:P17 wd:Q96. #Mexico country
SERVICE wikibase:label { bd:serviceParam wikibase:language "en"}
}"""
def get_results(endpoint_url, query):
user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1])
# TODO adjust user agent; see https://w.wiki/CX6
sparql = SPARQLWrapper(endpoint_url, agent=user_agent)
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
return sparql.query().convert()
results = get_results(endpoint_url, query)
for result in results["results"]["bindings"]:
print(result)
此代码为我提供了我需要的数据,但我在尝试使用此行获取此信息时遇到问题:
results.to_csv('results.csv', index=False)
出现此错误:
'dict' object has no attribute 'to_csv'
我将 pandas 和 numpy 导入这样做,但我仍然遇到问题,所以我想知道如何将此结果放入某种格式中,以使用获得的数据创建我的 csv 文件。
这里有一些屏幕截图。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
results
是一个 字典,即无法调用方法to_csv
的 Python 数据结构。为了安全地存储 python 字典中的 csv,您可以使用外部库(另请参阅文档< /a> 在 python.org 上)。
具体的解决方案取决于您确切想要导出的(元)数据。下面我假设您想要存储
org
和orgLabel
的value
。输出是:
results
is a dictionary, that is a python data structure which you can't invoke a methodto_csv
on.For safely storing a csv from a python dictionary you can use external libraries (see also the documentation on python.org).
The specific solution depends on which (meta)data you exactly want to export. In the following I assume that you want to store the
value
fororg
andorgLabel
.And the output is:
作为一个提交者
https://github.com/WolfgangFahl/pyLoDStorage
我要指出的是,SPARQL 类pyLodStorage 的明确目的是使到其他格式的转换变得简单。
结果:
当然,您可以直接通过 python API 获得相同的结果:
As a committer of
https://github.com/WolfgangFahl/pyLoDStorage
i am going to point out that the SPARQL class of pyLodStorage is explicitly there to make conversion to other formats simple.
result:
for course you can get the same result directly via the python APIs: