使用Python rdflib:如何在sparql查询中包括文字? [英] Using Python rdflib: how to include literals in sparql queries?
问题描述
我可以在查询中包含URI和变量,但不能 在查询中包含文字.
I can include URIs and variables in my queries, but I can't include literals in my queries.
在这里,我有一些代码可以成功读取RDF文件,找到 使用skos:prefLabels将所有RDF增加三倍,对它们进行计数,然后 从一组关键字中识别出几个特定的关键字:
Here, I have some code which successfully reads an RDF file, finds all the RDF triples with skos:prefLabels, counts them, and then identifies a couple of specific ones from a set of keywords:
import rdflib.plugins.sparql as sparql
import rdflib
import rdflib.graph as g
graph = g.Graph()
# Read the RDF file
graph.parse(
'h:\......SKOSTaxonomy.rdf',
format='xml')
# Build and execute the query
q = sparql.prepareQuery('SELECT ?s ?p ?o WHERE { ?s ?p ?o .}')
p = rdflib.URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")
qres = graph.query(q, initBindings = {'p' : p})
print len(qres)
# Look for keywords among the results
keywords = set([u'Jackknifing', 'Technology-mapping', 'Something random'])
for (subj, pred, obj) in qres:
if obj.value in keywords:
print obj.value
按预期,此代码将打印:
As expected, this code prints:
2299
Jackknifing
Technology-mapping
因为Jackknifing和Technology-mapping是文件中的prefLabel.
since Jackknifing and Technology-mapping are prefLabels in the file.
我真正想做的是构造并执行一个Sparql查询来 依次寻找每个关键字.但这就是我解脱的地方 因为我无法在查询中输入字符串.我已经尝试过了 例如:
What I really want to do is to construct and execute a Sparql query to look for each keyword in turn. But this is where I come unstuck, because I can't put a string into the query. I have tried this, for example:
o = rdflib.Literal(u'Jackknifing')
qres = graph.query(q, initBindings = {'p' : p, 'o' : o})
但是qres为空.我也尝试过将文字明确地放入 查询,例如
but qres is empty. I have also tried putting a literal explicitly into the query, e.g.
q = sparql.prepareQuery('SELECT ?s ?p WHERE { ?s ?p "Technology-mapping" .}')
qres = graph.query(q, initBindings = {'p' : p})
但是也会返回一个空结果.
but that returns an empty result too.
查询中如何包含文字?
推荐答案
如果数据中的文字具有数据类型或带有语言标签的字符串,则将插入一个普通文字,即没有数据类型或语言标签的文字查询不匹配.
If the literals in your data have datatypes, or are strings with language tags, then a plain literal, that is, one without a datatype or language tag, injected into the query won't match.
RDFLib 关于文字的文档显示了使用数据类型创建文字的方法,但没有使用语言标签创建一个示例的示例.但是,文档还附带了源代码
和 Literal
的
The RDFLib docs on Literals show ways of creating literals with datatypes, but don't have an example of creating one with a language tag. However, the docs also have the source attached
and the signature for Literal
's __new__
is:
static __new__(lexical_or_value, lang=None, datatype=None, normalize=None)
由于数据中的文字具有语言标签('en'
),因此您应将文字创建为
Since the literal in your data has a language tag ('en'
), you should to create your literal as
o = rdflib.Literal(u'Jackkifing',lang='en')
以便将语言标签与文字相关联.
so that the language tag is associated with the literal.
这篇关于使用Python rdflib:如何在sparql查询中包括文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!