close
DBpedia是一項從維基百科萃取內容的專案計畫,其內容均屬公開,下面開始介紹如何使用Java直接存取DBpeida內容。
首先,要先下載Jena的jar檔,因為要使用SPARQL來搜尋DBPedia的資源。
https://jena.apache.org/download/index.cgi
然後新增一個 Eclipse 專案,並且將此檔案中的jar通通import到這個專案中。
下述為程式碼,資料來源是: http://dbpedia.org/sparql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package DBPedia; | |
import org.apache.jena.query.ParameterizedSparqlString; | |
import org.apache.jena.query.QueryExecution; | |
import org.apache.jena.query.QueryExecutionFactory; | |
import org.apache.jena.query.ResultSet; | |
import org.apache.jena.query.ResultSetFactory; | |
import org.apache.jena.query.ResultSetFormatter; | |
import org.apache.jena.rdf.model.Literal; | |
import org.apache.jena.rdf.model.ResourceFactory; | |
public class DBPedia { | |
public static void main(String[] args) { | |
//下述是 SPARQL 的標準形式, 此類別可用參數設定來調整不同的結果 | |
ParameterizedSparqlString qs = new ParameterizedSparqlString(""+ | |
"prefix rdfs: \n"+ | |
"\n" + | |
"select ?resource where {\n" + | |
" ?resource rdfs:label ?label\n" + | |
"}" ); | |
//設定SPARQL的參數 | |
Literal london = ResourceFactory.createLangLiteral("London", "en"); | |
qs.setParam("label",london); | |
//顯示設定好的SPARQL的樣子 | |
System.out.println(qs); | |
//執行 SPARQL, 須設定Service來源 | |
QueryExecution exec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", qs.asQuery()); | |
// 通常會使用 results = exec.execSelect() | |
// 不過在此因為還要執行 Result 第二次,所以把它複製起來執行 | |
ResultSet results = ResultSetFactory.copyResults(exec.execSelect()); | |
while (results.hasNext()) { | |
System.out.println(results.next().get("resource")); | |
} | |
// 重輸出一次結果 | |
ResultSetFormatter.out(results); | |
} | |
} |
輸出的結果:
全站熱搜