前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >sparql语句进行查询

sparql语句进行查询

作者头像
DC童生
发布2019-05-07 11:11:18
2.1K0
发布2019-05-07 11:11:18
举报
文章被收录于专栏:机器学习原理机器学习原理

depedia

1、打开网站:http://dbpedia.org/sparql/ 2、查询有哪些书和书的简介 输入:

代码语言:javascript
复制
SELECT ?book ?com
WHERE 
{
  ?book rdf:type dbo:Book.
  ?book rdfs:comment ?com.
}

结果:

image.png

3、程序进行查询 安装SPARQLWrapper

代码语言:javascript
复制
from SPARQLWrapper import SPARQLWrapper, JSON
import json
sparql = SPARQLWrapper("http://dbpedia.org/sparql")

sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?book ?com
    WHERE 
    {
      ?book rdf:type dbo:Book.
      ?book rdfs:comment ?com.
    }
""")
#英语的过滤语言的简写是EN,在这里中文语言是ZH,FILTER是一个过滤器
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
# result_1=json.loads(results)
print(results)
for result in results["results"]["bindings"]:
    print(result["name"]["value"],result["date"]["value"],result["abstract"]["value"],"\n")

完整查询

代码语言:javascript
复制
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX dbo: <http://dbpedia.org/ontology/>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>

    Select distinct ?birthdate ?thumbnail ?scientist ?name ?description WHERE {
    ?scientist rdf:type dbo:Scientist ;
               dbo:birthDate ?birthdate ;
               rdfs:label ?name ;
               dct:description ?description
    FILTER ((lang(?name)="en")&&(lang(?description)="en")&&(STRLEN(STR(?birthdate))>6)&&(SUBSTR(STR(?birthdate),6)=STR("05-14")) ).
    OPTIONAL { ?scientist dbo:thumbnail ?thumbnail .} 
    } ORDER BY ?birthdate
    """

wikidata

1、网站:https://query.wikidata.org/ 2、sparql语句查询有哪些猫

代码语言:javascript
复制
SELECT ?item ?itemLabel 
WHERE 
{
  ?item wdt:P31 wd:Q146.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "zh". }
}
  • 以中文进行反向排序

order by desc(?itemLabel)

  • 解释 所有属性是猫的实体, wdt表示关系,P31表示性质 wd表示实体,Q146表示猫 3、查询结果

image.png 4、练习:查询中国唐朝的皇帝有哪些? 步骤1:从一个实体出发 wikidata查一个具体的皇帝 找到属性和实体代号 P39职业,Q268218,中国皇帝

代码语言:javascript
复制
SELECT ?person ?personLabel 
WHERE 
{
  ?person wdt:P39 wd:Q268218.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "zh". }
}
order by desc(?personLabel) 

结果如下:查到了中国所有的皇帝

image.png

步骤二: 再添加条件 朝代P27,唐朝,Q9683

代码语言:javascript
复制
SELECT ?person ?personLabel 
WHERE 
{
  ?person wdt:P39 wd:Q268218.
  ?person wdt:P27 wd:Q9683
  SERVICE wikibase:label { bd:serviceParam wikibase:language "zh". }
}
order by desc(?personLabel) 

结果:

image.png

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.04.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • depedia
  • wikidata
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档