Skip to main content
 首页 » 编程设计

python之在三元组中添加空白节点

2025年05月04日8dflying

下面编写的代码给出了以下输出:

代码:

person = BNode() 
dataStore.add((URIRef(stringrd),FOAF_NS['knows'],person)) 
dataStore.add((person,FOAF_NS['Person'],URIRef(fetchKnowsRowString))) 
dataStore.add((person,TRUST_NS['hasValue'],Literal(trustString))) 

输出:

<rdf:Description rdf:about="http://www.iamresearcher.com/profiles/id/luc.moreau"> 
  <foaf:knows rdf:nodeID="kdOAGjqG160"/> 
</rdf:Description> 
 
<rdf:Description rdf:nodeID="kdOAGjqG160"> 
  <t:data>1</t:data> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/patrick.hayes"/> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/christian.queinnec"/> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/thanassis.tiropanis"/> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/ian.foster"/> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/nicholas.gibbins"/> 
</rdf:Description> 

但是我需要下面的输出,你能指导一下它有什么问题吗?

<rdf:Description rdf:about="http://www.iamresearcher.com/profiles/id/luc.moreau"> 
<foaf:knows> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/patrick.hayes"> 
    <t:data>1</t:data> 
  </foaf:Person> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/christian.queinnec"> 
    <t:data>1</t:data> 
  </foaf:Person> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/thanassis.tiropanis"> 
    <t:data>1</t:data> 
  </foaf:Person> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/ian.foster"> 
    <t:data>1</t:data> 
  </foaf:Person> 
  <foaf:Person rdf:resource="http://www.iamresearcher.com/profiles/id/nicholas.gibbins"> 
    <t:data>1</t:data> 
  </foaf:Person> 
</foaf:knows> 
</rdf:Description> 

提前致谢。

请您参考如下方法:

看来您在 bNode person 上以某种方式错误地循环。您始终使用相同的 bNode,这可能是错误的原因。

所以如果你的代码看起来像......

person = BNode() 
for (fetchKnowsRowString, trustString) in friends: 
   dataStore.add((URIRef(stringrd),FOAF_NS['knows'],person)) 
   dataStore.add((person,FOAF_NS['Person'],URIRef(fetchKnowsRowString))) 
   dataStore.add((person,TRUST_NS['hasValue'],Literal(trustString))) 

那么错误就是你使用的是同一个bNode实例。您的代码应该类似于下面的代码片段。请注意,bNode 创建是在循环内,这是主要区别。

for (fetchKnowsRowString, trustString) in friends: 
   person = BNode() 
   dataStore.add((URIRef(stringrd),FOAF_NS['knows'],person)) 
   dataStore.add((person,FOAF_NS['Person'],URIRef(fetchKnowsRowString))) 
   dataStore.add((person,TRUST_NS['hasValue'],Literal(trustString)))