You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中读取OWL文件并生成含文本值与类型的DataFrame

在R语言中读取OWL本体并生成含文本值与类型标注的DataFrame

要处理Unified Cybersecurity Ontology(UCO)这类OWL文件,生成包含可读文本值和本体实体类型的DataFrame,可以用rdflib包完成,以下是修正后的完整实现:

完整代码

library(rdflib)

# 直接读取线上UCO本体(无需本地下载)
graph <- owl_read("https://github.com/Ebiquity/Unified-Cybersecurity-Ontology/blob/master/uco_1_5.owl?raw=true")

# 1. 提取实体的可读标签(rdfs:label)
label_triples <- as.data.frame(graph %>% filter(predicate == "rdfs:label"))
colnames(label_triples) <- c("subject", "predicate", "text_value")

# 2. 提取实体的类型三元组,细化类型分类
type_triples <- as.data.frame(graph %>% filter(predicate == "rdf:type"))
colnames(type_triples) <- c("subject", "predicate", "type_raw")

# 定义类型映射规则,匹配具体的本体类型
classify_entity_type <- function(raw_type) {
  switch(raw_type,
         "owl:Class" = "Class",
         "owl:DatatypeProperty" = "Datatype Property",
         "owl:ObjectProperty" = "Object Property",
         "owl:AnnotationProperty" = "Annotation Property",
         "rdfs:Class" = "Class",
         NA)
}

# 添加细化后的类型列
type_triples$type <- sapply(type_triples$type_raw, classify_entity_type)

# 3. 提取子类关系(rdfs:subClassOf)并标记类型
subclass_triples <- as.data.frame(graph %>% filter(predicate == "rdfs:subClassOf"))
colnames(subclass_triples) <- c("subject", "predicate", "parent_class")
subclass_triples$type <- "Subclass"

# 4. 合并标签与类型数据,保留有效条目
# 合并类型三元组与标签
result_df <- merge(label_triples[, c("subject", "text_value")], 
                   type_triples[, c("subject", "type")], 
                   by = "subject", all.x = TRUE)

# 合并子类数据
subclass_labels <- merge(subclass_triples[, c("subject", "type")], 
                         label_triples[, c("subject", "text_value")], 
                         by = "subject", all.x = TRUE)

# 合并所有有效数据并去重
result_df <- rbind(result_df, subclass_labels)
result_df <- result_df[!is.na(result_df$type), ]
result_df <- unique(result_df)

# 调整列顺序为需求的「文本值」「类型」
result_df <- result_df[, c("text_value", "type")]

# 查看结果
head(result_df)

关键修正与说明

  • 提取可读文本值:通过rdfs:label三元组获取本体实体的人类可读文本,替代原代码中直接使用URI的方式
  • 细化类型分类:不再笼统分为「Class/Property」,而是精确区分Class、Subclass、Datatype Property、Object Property、Annotation Property等具体类型
  • 合并有效数据:整合类型声明与子类关系,确保所有实体的文本值与类型一一对应,去除无效的NA条目
  • 直接读取线上本体:使用带?raw=true的URL直接读取原始OWL文件,避免本地路径的兼容性问题

输出示例

text_value             type
1          ActionType             Class
2         ActionStatus             Class
3         ArtifactRole             Class
4        AttackPattern             Class
5           AttackTool             Class
6 AttributionInformation Subclass

内容的提问来源于stack exchange,提问作者Eleni Kalaitzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:27:45