python - 从 RDF 查询结果打印/解析 JSON 对象

标签 python json parsing printing rdflib

我正在尝试解析来自 Sesame 的 SPARQL 查询的结果。 我找到了示例代码,下面是相关部分,我在下面显示了我的结果。

(response, content) = httplib2.Http().request(endpoint, 'POST', urllib.urlencode(params), headers=headers)

print "Response %s" % response.status
results = json.loads(content)
print "\n".join([result['type']['value'] for result in results['results']['bindings']])

{

   "head": {

       "vars": [ "costar", "movie" ]

   },

   "results": {

       "bindings": [

           {

               "costar": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.connie_nielsen" },

               "movie": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.basic_2003" }

           },

           {

               "costar": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.timothy_daly" },

               "movie": { "type": "uri", "value": "http:\/\/rdf.freebase.com\/ns\/en.basic_2003" }

           },


      ]

   }

}     

但是我得到这个错误:

Traceback (most recent call last):
  File "C:\Software\rdflib\movieSparqlQuery.py", line 45, in <module>
    print "\n".join([result['type']['value'] for result in results['results']['b
indings']])
KeyError: 'type'
Press any key to continue . . .

如何更改“打印”语句?

我想看到的是像在同一行的costar和电影名称:

http://rdf.freebase.com/ns/en.connie_nielsen  http://rdf.freebase.com/ns/en.basic_2003

稍后,我将剥离 namespace 。

谢谢!

最佳答案

您收到的错误表明 result 字典没有关键字 'type'。如果仔细检查,results['results']['bindings'] 的每个元素都是一个包含两个键的字典:'costar''movie' ,因此您的 result 变量将是包含这两个键的字典。

result['costar']result['movie'] 也是一个有两个键的字典:'type'“值”。你真正想要的是构建一个包含 result['costar']['value']result['movie']['value'] 的字符串空间。给定一个结果,您可以通过以下方式实现:

" ".join(result[var]['value'] for var in results['head']['vars'])

现在要打印一个包含所有由换行符分隔的 Actor 和电影的字符串,您只需将打印语句修改为

print "\n".join([" ".join(result[var]['value'] for var in results['head']['vars']) for result in results['results']['bindings']])

关于python - 从 RDF 查询结果打印/解析 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930057/

相关文章:

python - 尝试使用 for 循环比较文本

python - 使用来自文件的输入创建字典

c++ - 将 boost::spirit 符号表作为继承属性传递到语法中

node.js - 在node.js express中通过body-parser POST表单数据时,数据始终为 'undefined'

python - Pandas 中的浮点索引的目的是什么?

python - 矢量化以计算许多距离

php - 检索通过 POST 发送到 PHP 脚本的 json 字段时出错

java - 如何为名称/值结构创建 JSON 模式?

json - Haskell Data.Decimal 作为 Aeson 类型

php - 操作 .ini 文件的良好 PHP 类