如何使用R将百分比编码的URI转换为IRI(RDF关联数据场景)
Hey there! Converting percent-encoded URIs to valid IRIs for RDF linked data in R is totally doable, and we can align it with the W3C spec you referenced. Let's break this down with practical code examples:
First, a quick recap of the key steps from the spec:
- Decode percent-encoded byte sequences into UTF-8 characters (since IRIs use Unicode/UTF-8)
- Preserve the structure of the original URI (like namespace prefixes or HTTP protocols)
- Ensure the resulting IRI is well-formed for use in RDF datasets
We can build a straightforward function to handle both prefixed URIs (like your test:Value_ONE%20OR%20TWO example) and absolute URIs. We'll use base R's built-in URLdecode() function, which handles UTF-8 decoding perfectly for this use case:
uri_to_iri <- function(uri) { # Handle prefixed URIs (e.g., test:xyz) if (grepl("^[a-zA-Z0-9]+:", uri)) { # Split into namespace prefix and local part ns_prefix <- sub("^(.*?:).*", "\\1", uri) local_segment <- sub("^.*?:", "", uri) # Decode the percent-encoded local segment decoded_local <- URLdecode(local_segment, encoding = "UTF-8") # Combine back into a valid IRI iri <- paste0(ns_prefix, decoded_local) } else { # Handle absolute URIs (e.g., http://example.com/foo%20bar) iri <- URLdecode(uri, encoding = "UTF-8") } return(iri) } # Test with your sample URI sample_uri <- "test:Value_ONE%20OR%20TWO" converted_iri <- uri_to_iri(sample_uri) cat("Converted IRI:", converted_iri, "\n") # Output: Converted IRI: test:Value_ONE OR TWO
For extra peace of mind, you can use the rdflib package to validate that your converted IRI is properly formatted for RDF:
# Install if you haven't already # install.packages("rdflib") library(rdflib) # Create and validate an IRI object validated_iri <- iri(converted_iri) print(validated_iri)
This will throw an error if the IRI is malformed, so you can be confident it's compliant with linked data standards.
内容的提问来源于stack exchange,提问作者Tim

