上一篇文章 中,我們了解了SPARQL、SPARQL Endpoint,并簡單做了一個SPARQLWrapper.js,來從DBpedia中查詢了一些數據。
本文則嘗試利用SPARQLWrapper.js來讀取DBpedia的數據,并顯示出來。
?
目標
通過輸入一個英文單詞,然后返回WIKI中相關的信息。
那么主要要解決的問題就是怎樣的SPARQL語句能夠查詢到我們需要的東西。
?
先看一段簡單的SPARQL查詢語句
PREFIX : < http: // aabs.purl.org / music# > SELECT ?instrument WHERE { :andrew :playsInstrument ?instrument . }
首先定義一個域名空間http://aabs.purl.org/music#。
然后選擇這樣子的instrument變量,他滿足:
主語是http://aabs.purl.org/music#andrew,謂語是http://aabs.purl.org/music#playsInstrument,賓語是該instrument。
?
bif:contains()
bif:contains()是contains()函數的變種函數,顧名思義是判斷是否包含的函數。
利用這個我們能查詢到我們需要的數據了。
prefix foaf: < http: // xmlns.com / foaf / 0.1 /> select distinct ?url ?alma ?comment where { ?s foaf:name ?sname . ?sname bif: contains ' China ' . ?s foaf:depiction ?url . ?s dbpedia - owl:wikiPageExternalLink ?alma . ?s rdfs:comment ?comment . } limit 10
這段SPARQL語句是查詢包含China的名字的詞條,然后將其圖片的url、homepage的url,以及簡介返回回來。
下面讓我們把整個程序寫完。
?
完整代碼
< html > < head > < meta charset ="utf-8" > < title > SPARQL DEMO </ title > < script src ="SPARQLWrapper.js" ></ script > < script > var $ = function (id){ return document.getElementById(id); }, sparql = new SPARQLWrapper( " http://dbpedia.org/sparql " ), results = []; function getInfo(name){ name = name.replace( / \s / g, " _ " ); var command = " prefix foaf: <http://xmlns.com/foaf/0.1/> " + " select distinct ?url ?alma ?comment " + " where { " + " ?s foaf:name ?sname . " + " ?sname bif:contains ' " + name + " '. " + " ?s foaf:depiction ?url . " + " ?s dbpedia-owl:wikiPageExternalLink ?alma . " + " ?s rdfs:comment ?comment . " + " } " + " limit 10 " ; sparql.setQuery(command); sparql.query( function (json){ showInfo((eval( " ( " + json + " ) " )).results.bindings); }); } function showInfo(results){ var text = "" ; if (results.length !== 0 ){ for ( var i = 0 ; i < results.length; i ++ ){ text += " <img src = ' " + results[i].url.value + " ' /><br /> " ; text += " homepage: " + " <a href = ' " + results[i].alma.value + " ' > " + results[i].alma.value + " </a><br /> " ; text += " <p> " + results[i].comment.value + " </p><br /><br /><br /> " ; $( " result " ).innerHTML = text; } } else { $( " result " ).innerHTML = " 沒有任何相關信息! " ; } } </ script > </ head > < body > < p > 目前只支持英文查詢。 </ p > < input type ="text" id ="name" /> < input type ="button" onclick ="getInfo(document.getElementById('name').value);" value ="Wiki Search" /> < div id ="result" ></ p > </ body > </ html >
?
遺留問題
不太清楚中文怎么查詢,如有知道的朋友,麻煩告知一下,謝謝。
?
例子
http://pan.baidu.com/share/link?shareid=293219&uk=855675565
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
