使用Owlready访问本体实体注解属性(如definition)报错的解决方法
如何用Owlready访问HumanDO本体的注解属性(比如definition)
需求:使用Owlready库读取HumanDO.owl本体中实体的注解属性,例如获取「冲动控制障碍」的definition属性。
原测试代码:
from owlready2 import * onto = get_ontology("./HumanDO.owl").load() for subclass_of_mental_health in list(onto.search(label ="disease of mental health")[0].subclasses()): print(subclass_of_mental_health.id, subclass_of_mental_health.label) # 可正常输出 print(subclass_of_mental_health.definition) # 执行报错
报错信息:
['DOID:10937'] ['impulse control disorder'] --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_14348\3127299132.py in <module> 1 for subclass_of_mental_health in list(onto.search(label ="disease of mental health")[0].subclasses()): 2 print(subclass_of_mental_health.id, subclass_of_mental_health.label) ----> 3 print(subclass_of_mental_health.definition) E:\Python\PythonInstall\envs\new\lib\site-packages\owlready2\entity.py in __getattr__(Class, attr) 592 else: 593 Prop = Class.namespace.world._props.get(attr) --> 594 if not Prop: raise AttributeError("'%s' property is not defined." % attr) 595 if issubclass_python(Prop, AnnotationProperty): 596 attr = "__%s" % attr # Do NOT cache as such in __dict__, to avoid inheriting annotations AttributeError: 'definition' property is not defined.
当前仅能通过点标记访问id和label属性,其他注解属性无法直接访问,卡在读取环节。
问题原因
Owlready中,id和label是库预定义的常用属性,可直接通过点访问;但像definition这类本体自定义的注解属性,需要先明确对应的AnnotationProperty对象,或使用通用方法获取注解内容。
解决方案
HumanDO本体中,definition对应的是IAO_0000115这个标准注解属性,以下两种方法可获取其值:
方法1:使用get_annotation方法获取注解
通过实体的get_annotation方法,传入对应的注解属性对象来获取值:
from owlready2 import * onto = get_ontology("./HumanDO.owl").load() # 获取definition对应的注解属性对象 definition_prop = onto.get_annotation_property("http://purl.obolibrary.org/obo/IAO_0000115") # 遍历子类并读取definition mental_health_disease = onto.search(label ="disease of mental health")[0] for subclass in list(mental_health_disease.subclasses()): print(subclass.id, subclass.label) # 获取并打印definition注解值 definition = subclass.get_annotation(definition_prop) print(definition)
方法2:通过属性IRI直接访问
如果本体已绑定前缀,可直接通过前缀+属性名访问;未绑定则需使用完整IRI:
from owlready2 import * onto = get_ontology("./HumanDO.owl").load() # 遍历子类并读取definition(使用完整IRI) mental_health_disease = onto.search(label ="disease of mental health")[0] for subclass in list(mental_health_disease.subclasses()): print(subclass.id, subclass.label) # 通过完整IRI访问注解属性 print(subclass["http://purl.obolibrary.org/obo/IAO_0000115"])
额外说明
若不确定目标注解属性的IRI,可通过onto.annotation_properties()列出本体中所有注解属性,从中查找对应属性的IRI信息。
内容的提问来源于stack exchange,提问作者ASLAN
相关产品推荐
相关产品推荐

