我将使用Apache Jena并将RDF作为输入格式。但我有CSV格式的数据。我研究了很多,找不到转换它的方法。有谁知道如何有效地做到这一点。
我已经通过像xml123这样的工具,但下载链接无效。
答案 0 :(得分:6)
使用jena-arq和jena-csv(均为v3.0.1),以下方式对我有用:
public static void main(String ... strings) throws Exception {
CSV2RDF.init();
//load through manager:
//Model m = RDFDataMgr.loadModel("test.csv") ;
//classic way to load:
Model m = ModelFactory.createDefaultModel();
try (InputStream in = JenaCSVTest.class.getResourceAsStream("/test.csv")) {
m.read(in, "http://example.com", "csv");
}
m.setNsPrefix("test", "http://example.com#");
m.write(System.out, "ttl");
}
输入(test.csv):
Town,Population
Southton,123000
Northville,654000
输出(乌龟中的rdf):
@prefix test: <http://example.com#> .
[ test:Population "123000"^^<http://www.w3.org/2001/XMLSchema#double> ;
test:Town "Southton" ;
<http://w3c/future-csv-vocab/row>
1
] .
[ test:Population "654000"^^<http://www.w3.org/2001/XMLSchema#double> ;
test:Town "Northville" ;
<http://w3c/future-csv-vocab/row>
2
] .
请参阅官方文档jena-csv
<强>更新强>:
开始 jena-3.10.0 jena-csv已退役。 最后一个jena-csv版本是3.9.0。 相反,您可以使用任何其他csv2rdf转换器。 例如,tarql。
com.github.tarql:tarql
版本v1.2
的快速演示示例(通过jitpack.io获得 - 似乎没有maven-central版本):
Path file = Paths.get(JenaCSVTest.class.getResource("/test.csv").toURI());
String base = "http://example.com#";
Model m = ModelFactory.createDefaultModel().setNsPrefix("xsd", XSD.getURI()).setNsPrefix("test", base);
Graph g = m.getGraph();
CSVOptions op = new CSVOptions();
op.setDefaultsForCSV();
String query = "PREFIX test: <" + base + ">\n" +
"PREFIX xsd: <" + XSD.getURI() + ">\n" +
"CONSTRUCT {\n" +
" ?Row a test:Row;\n" +
" test:town ?town;\n" +
" test:population ?population;\n" +
"} \n" +
"WHERE {\n" +
" BIND (BNODE() AS ?Row)\n" +
" BIND (xsd:string(?Town) AS ?town)\n" +
" BIND (xsd:integer(?Population) AS ?population)\n" +
"}";
TarqlQuery q = new TarqlQuery(QueryFactory.create(query));
InputStreamSource src = InputStreamSource.fromFilenameOrIRI(file.toUri().toString());
TarqlQueryExecution qe = TarqlQueryExecutionFactory.create(q, src, op);
qe.execTriples().forEachRemaining(g::add);
m.write(System.out, "ttl");
此代码段将生成以下RDF:
@prefix test: <http://example.com#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
[ a test:Row ;
test:population 123000 ;
test:town "Southton"
] .
[ a test:Row ;
test:population 654000 ;
test:town "Northville"
] .
答案 1 :(得分:0)
您还可以使用https://github.com/AtomGraph/CSV2RDF来构建通用CSV / RDF图,然后使用SPARQL CONSTRUCT
查询对其进行转换。 (免责声明:我是作者)