在Google Colab用Owlready2查询Quran本体时qur:前缀未定义错误求助
解决Owlready2中SPARQL查询的"Undefined prefix 'qur:'"错误
问题原因
Owlready2的default_world.sparql()不会自动导入本体文件中定义的XML前缀,必须显式为SPARQL查询注册前缀,或者直接使用本体的命名空间对象来构建查询。
解决方案1:显式注册qur前缀
在执行SPARQL查询前,将qur前缀及其对应的URI注册到default_world的SPARQL命名空间中:
from owlready2 import * # 添加本体路径并加载本体 onto_path.append("/gdrive/MyDrive/Quran Corpus") go = get_ontology("/gdrive/MyDrive/Quran Corpus/quran_data_full.owl").load() # 注册qur前缀到SPARQL命名空间 default_world.sparql_namespaces["qur"] = "http://quranontology.com/Resource/" # 执行SPARQL查询 d = list(default_world.sparql(""" SELECT Distinct ?verse ?text ?word1 ?wordText1 WHERE { ?verse rdf:type qur:Verse. ?verse rdfs:label ?textSimple. ?verse qur:DisplayText ?text. ?word1 qur:IsPartOf ?verse. ?word1 rdfs:label ?wordText1. ?word1 qur:WordLemma ?wordLema1. ?word1 qur:WordRoot ?wordRoot1. FILTER(?wordText1 = "الوصية"@ar || ?wordLema1 = "الوصية"@ar || ?wordRoot1 = "الوصية"@ar) } LIMIT 25 """))
解决方案2:使用本体命名空间对象(更推荐)
直接通过加载后的本体获取命名空间,避免手动管理前缀,更不易出错:
from owlready2 import * # 添加本体路径并加载本体 onto_path.append("/gdrive/MyDrive/Quran Corpus") go = get_ontology("/gdrive/MyDrive/Quran Corpus/quran_data_full.owl").load() # 获取qur命名空间(本体的base URI就是qur对应的URI) qur = go.get_namespace("http://quranontology.com/Resource/") # 使用Owlready2的查询语法(无需手动写SPARQL前缀) d = list(default_world.sparql(""" SELECT Distinct ?verse ?text ?word1 ?wordText1 WHERE { ?verse rdf:type %s. ?verse rdfs:label ?textSimple. ?verse %s ?text. ?word1 %s ?verse. ?word1 rdfs:label ?wordText1. ?word1 %s ?wordLema1. ?word1 %s ?wordRoot1. FILTER(?wordText1 = "الوصية"@ar || ?wordLema1 = "الوصية"@ar || ?wordRoot1 = "الوصية"@ar) } LIMIT 25 """ % (qur.Verse, qur.DisplayText, qur.IsPartOf, qur.WordLemma, qur.WordRoot)))
额外说明
- 原代码中
obo = get_namespace("/gdrive/MyDrive/Quran Corpus/")是错误的,get_namespace需要传入本体的URI前缀(如http://quranontology.com/Resource/),而非本地文件路径,这行代码可以删除。 - 本体文件中
xmlns="http://quranontology.com/Resource/"表示这是默认命名空间,所有未加前缀的实体都属于该命名空间,也可以在SPARQL中直接使用<http://quranontology.com/Resource/Verse>这种完整URI替代qur:Verse,但显式注册前缀更简洁。
内容的提问来源于stack exchange,提问作者Reem
相关产品推荐
相关产品推荐

