在RDFLIB和Python for Sparql update语句中使用具有存储值的变量

2024-05-12 23:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是RDFLIB的新手,我正在尝试学习如何使用^{}语句从CSV文件中不断更新本体中个人的数据属性值。我正在使用pandas dataframe来做这件事,但我现在被卡住了

如果我直接使用值,如23、34.6、13330等,我能够成功地做到这一点。但我的挑战是,如果我从CSV读取数据并将其存储为变量(如“x”),这将不起作用。以下是我的代码中工作正常的部分:

g.update( """ DELETE { ?Product myontology:LifecycleData ?lifecycle } INSERT { ?Product myontology:LifecycleData 243 } WHERE { ?Product myontology:LifecycleData ?lifecycle . } """)

现在,如果我将值243赋给x,即x=243,并在上面的代码中将243替换为x,我会得到错误。 有人能帮我处理一下吗?如果需要的话,我可以提供更多的信息,但我会尽量简短。 先谢谢你


Tags: 文件csv数据代码pandas属性本体语句
1条回答
网友
1楼 · 发布于 2024-05-12 23:08:26

我会将您的字符串查询构建与查询提交分开,并(可视化)测试查询,确保其正确性,如下所示:

q = """
    DELETE {
        ?Product myontology:LifecycleData ?lifecycle 
    }
    INSERT {
        ?Product myontology:LifecycleData xxx 
    }
    WHERE {
        ?Product myontology:LifecycleData ?lifecycle  
    }
    """.replace("xxx", str(df.tail(1)['Usecycle left'].values[0]))

# I like to use replace() rather than string templating
# so I don't have to escape characters like { in the query

print(q)  # does it look like you expect it to at this point?

# then...
g.update(
    q, 
    initNs={
        "myontology": Namespace("http://example.com/myontology#")
    }
)

相关问题 更多 >