如何解决owlready2中SPARQL语言过滤返回空集的问题?
问题:Owlready2中SPARQL语言过滤返回空集的解决办法
问题描述
我在Google云端硬盘的“Quran Corpus”文件夹中存储了本体文件quran_data_full.owl。在Apache Jena Fuseki中执行SPARQL查询能得到正确的阿拉伯语结果,但把查询复制到Google Colab的Owlready2代码中后,加入FILTER langMatches(lang(?text),"ar")语句就返回空集;删除该语句能返回包含阿拉伯语和英语的结果,我需要仅显示阿拉伯语文本。
原代码如下:
from owlready2 import * onto_path.append("/gdrive/MyDrive/Quran Corpus") go = get_ontology("/gdrive/MyDrive/Quran Corpus/quran_data_full.owl").load() obo = get_namespace("/gdrive/MyDrive/Quran Corpus/") d = list(default_world.sparql(""" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX qur: <http://quranontology.com/Resource/> SELECT ?verse ?text WHERE {?verse rdf:type qur:Verse. ?verse qur:DiscussTopic ?topic. ?verse rdfs:label ?text. ?topic qur:TopicCompleteName ?topicName. FILTER (REGEX(STR(?topicName), "زكاة" ,"i")). FILTER langMatches(lang(?text),"ar") } """))
解决方案
- 确认实际语言标签格式:Owlready2对语言标签的解析逻辑和Jena Fuseki存在差异,先执行查询查看本体中
rdfs:label实际存储的语言代码,比如是否带区域后缀(如ar-SA)或大小写不一致。 - 调整过滤条件:如果实际语言标签是标准的
ar,可替换langMatches为直接匹配FILTER(lang(?text) = "ar");如果是带区域的标签,保留langMatches(lang(?text), "ar")即可兼容匹配。
修改后的代码示例
from owlready2 import * onto_path.append("/gdrive/MyDrive/Quran Corpus") go = get_ontology("/gdrive/MyDrive/Quran Corpus/quran_data_full.owl").load() obo = get_namespace("/gdrive/MyDrive/Quran Corpus/") # 第一步:查询所有相关文本的实际语言标签 lang_check = list(default_world.sparql(""" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX qur: <http://quranontology.com/Resource/> SELECT ?text (lang(?text) AS ?lang) WHERE {?verse rdf:type qur:Verse. ?verse qur:DiscussTopic ?topic. ?verse rdfs:label ?text. ?topic qur:TopicCompleteName ?topicName. FILTER (REGEX(STR(?topicName), "زكاة" ,"i")). } """)) print("实际语言标签:", lang_check) # 第二步:根据查询到的语言标签调整过滤条件 d = list(default_world.sparql(""" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX qur: <http://quranontology.com/Resource/> SELECT ?verse ?text WHERE {?verse rdf:type qur:Verse. ?verse qur:DiscussTopic ?topic. ?verse rdfs:label ?text. ?topic qur:TopicCompleteName ?topicName. FILTER (REGEX(STR(?topicName), "زكاة" ,"i")). # 根据实际查询结果修改,比如匹配标准ar标签 FILTER(lang(?text) = "ar") } """))
内容的提问来源于stack exchange,提问作者Reem
相关产品推荐
相关产品推荐

