如何解决使用 csv 文件创建 RDF 文件包含日期值作为输入
我有一个如图所示的数据,想把它转换成RDF文件。我使用了以下代码
#import libraries
import pandas as pd #for handling csv and csv contents
from rdflib import Graph,Literal,RDF,URIRef,Namespace #basic RDF handling
from rdflib.namespace import FOAF,XSD #most common namespaces
import urllib.parse #for parsing strings to URI's
#Read file
df=pd.read_csv("filename.csv",sep="\t",quotechar='"')
#creating graph
g = Graph()
continent = Namespace('http://example.org/continent/')
loc= Namespace('http://mylocations.org/addresses/')
schema = Namespace('http://schema.org/')
for index,row in df.iterrows():
g.add((URIRef(continent+row[0]),RDF.type,URIRef(continent+'Iso_code')))
g.add((URIRef(continent+row[1]),URIRef(continent+'Continent')))
g.add((URIRef(continent+row[2]),URIRef(continent+'Location')))
g.add((URIRef(continent+row[2]),URIRef(continent+'is_in'),URIRef(continent+row[1])))
g.add((URIRef(continent+row[2]),URIRef(continent+'total_cases'),Literal(row[4],datatype=XSD.integer)))
g.add((URIRef(continent+row[2]),URIRef(continent+'date'),Literal(row[3],datatype=XSD.date)))
# save graph
g.serialize('mycsv2rdf.ttl',format='turtle')
我是否正确创建了 rdf? 创建的文件有类似的数据。
@prefix ns1: <http://example.org/continent/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ns1:AFG a ns1:Iso_code .
ns1:Afghanistan a ns1:Location ;
ns1:date "0101-01-01"^^xsd:date,"0201-01-01"^^xsd:date,"0301-01-01"^^xsd:date,"0401-01-01"^^xsd:date,"0501-01-01"^^xsd:date,"0601-01-01"^^xsd:date,"2401-01-01"^^xsd:date,"2501-01-01"^^xsd:date,"2601-01-01"^^xsd:date,"2701-01-01"^^xsd:date,"2801-01-01"^^xsd:date,"2901-01-01"^^xsd:date ;
ns1:is_in ns1:Asia ;
ns1:total_cases 1,2,4 .
ns1:Asia a ns1:Continent .
值未按日期插入。帮我做我必须做的事。 如何将日期值插入图表中。
解决方法
不,您的数据在几个方面不正确:
- 您的日期需要正确解析。考虑使用 Python 的
datatime.strtotime()
,然后将日期对象提供给 RDFlib 的Literal
类 - 您已经声明了一个
Iso_code
类并创建了它的实例,例如ns1:AFG
,但您尚未将任何内容链接到它。
实际上,您的 RDF 都没有意义:您需要有一个主题,可能是 ns1:Afghanistan
(但请注意 ns1
的 URI 包含 /continent/
,但阿富汗不是大陆) 然后将 thigs 链接到它。您已经声明了一系列不相关的主题,例如ns1:AFG
、ns1:Afghanistan
、ns1:date
。
你可能想要这样的东西:
@prefix ns1: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix time: <http://www.w3.org/2006/time#> .
ns1:AFG a ns1:Iso_code .
ns1:Asia a ns1:Continent .
ns1:Afghanistan
a ns1:Location ;
ns1:hasIsoCode ns1:AFG ;
ns1:hasDatedCases [
time:hasTime "2020-02-24"^^xsd:date ;
ns1:totalCases 1 ;
ns1:newCases 1 ;
],[
time:hasTime "2020-02-25"^^xsd:date ;
ns1:totalCases 1 ;
ns1:newCases 0 ;
],...
ns1:is_in ns1:Asia ;
.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。