在Python中查询rdf/xml
以下代码:
import rdflib.graph as g
graph = g.Graph()
graph.parse('C:\\Python27\\phyton projects\\senticnet-3.0\\senticnet3.rdf.xml', format='xml')
print graph.serialize(format='pretty-xml')
在Python中返回的数据是:
<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF
xmlns:ns1="http://sentic.net/"
xmlns:ns2="http://sentic.net/api/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
>
<ns1:apisemantics>
<ns2:concept rdf:about="http://sentic.net/api/en/concept/love">
<ns1:apipolarity rdf:datatype="http://www.w3.org/2001/XMLSchema#float">0.667</ns1:apipolarity>
<ns1:apiattention rdf:datatype="http://www.w3.org/2001/XMLSchema#float">0</ns1:apiattention>
<ns1:apipleasantness rdf:datatype="http://www.w3.org/2001/XMLSchema#float">1</ns1:apipleasantness>
<ns1:apiaptitude rdf:datatype="http://www.w3.org/2001/XMLSchema#float">1</ns1:apiaptitude>
<ns1:apisemantics rdf:resource="http://sentic.net/api/en/concept/love_another_person"/>
<ns1:apisemantics rdf:resource="http://sentic.net/api/en/concept/beloved"/>
<ns1:apisemantics rdf:resource="http://sentic.net/api/en/concept/lust"/>
<ns1:apisemantics rdf:resource="http://sentic.net/api/en/concept/show_empathy"/>
<ns1:apisemantics rdf:resource="http://sentic.net/api/en/concept/sexuality"/>
<ns1:apisensitivity rdf:datatype="http://www.w3.org/2001/XMLSchema#float">0</ns1:apisensitivity>
<ns1:apitext>love</ns1:apitext>
</ns2:concept>
</ns1:apisemantics>
我该如何查询这个输出中的各种元素呢?
比如,我怎么才能获取到apipolarity
的值?
或者,我怎么才能获取到所有的apisemantics
,比如“love_another_person”、“beloved”等等?
编辑
我能这样获取数据:
qres = result.query(
"""SELECT ?subject ?predicate ?object
WHERE {
?subject ?predicate ?object.
}""")
for r in qres.result:
print str(r[0]), str(r[1]), str(r[2])
这返回了:
http://sentic.net/api/en/concept/a_lot_of_study http://sentic.net/apitext a lot of study
http://sentic.net/api/en/concept/a_lot_of_study http://sentic.net/apiaptitude -0.111
http://sentic.net/api/en/concept/a_lot_of_study http://sentic.net/apiattention -0.005
http://sentic.net/api/en/concept/a_lot_of_study http://sentic.net/apipolarity -0.064
http://sentic.net/api/en/concept/a_lot_of_study http://sentic.net/apipleasantness -0.074
那么我现在该如何将查询缩小到一个特定的概念,比如它的极性呢?
1 个回答
2
下面是一个示例查询,用来获取概念“a_little”的极性:
qres = result.query(
"""SELECT ?object
WHERE {
?subject ?predicate ?object
FILTER (?subject = <http://sentic.net/api/en/concept/a_little>)
FILTER (?predicate = <http://sentic.net/apipolarity>)
}""")
for r in qres.result:
print str(r[0])
编辑
根据Joshua的建议,改进了这个解决方案:
qres = result.query(
"""
prefix concept: <http://sentic.net/api/en/concept/>
prefix api: <http://sentic.net/api/>
SELECT ?polarity
WHERE {
concept:%s api:polarity ?polarity
}
"""%concept) #concept is passed through as a function parameter
for r in qres.result:
return str(r[0])