使用R将URI转换为IRI?

时间:2018-04-20 13:44:31

标签: r rdf linked-data

我正在使用R创建RDF链接数据。现在我有URI的样子:

test:Value_ONE%20OR%20TWO 

我想要使用正确的编码创建IRI。这里描述了URI到IRI的转换:

https://www.w3.org/International/iri-edit/draft-duerst-iri.html#URItoIRI

有人可以用示例R代码指导我将百分比编码的URI转换为IRI吗?

1 个答案:

答案 0 :(得分:1)

您必须使用逻辑,但下面适用于您发送的链接中的第一个示例。幸运的是,大部分转换可以在 R 基础上完成。我已经添加tidyverse只是为了提出计算方法。

地图只是tidyverse系列的apply版本,并通过列表或向量进行迭代。可以使用map_int/map_chr替换sapplymap/map2可以替换为lapply。只要你想在 R 中进行字符串操作(提取和替换),stringr就是你最好的朋友:

library(tidyverse)

testURI = 'http://www.example.org/D%C3%BCrst'
#testURI = 'test:Value_ONE%20OR%20TWO'

########################################
# extract any pattern that matches %\w\w
# "\w" is a regex representation for any character
# a "\" must be prepended to the regex in R
########################################

extractPerc <- testURI %>%
  str_extract_all(regex('(%\\w{2})+')) %>%
  unlist()

extractPercDecoded <- map_chr(extractPerc, URLdecode)

extractPercInt <- map_int(extractPercDecoded, utf8ToInt)

############################################
# Keep as a list so the Hex code isn't converted to it's
# character representation or it's numeric default
############################################

extractPercHex <- map(extractPercInt, as.hexmode)


#####################################################
# iterate over the string and replace the %s with the hexs
# There's definitely a better way to replace the %-html representation
# with the hex representation, but I can't quite figure it out
####################################################

newURI = testURI

map2(extractPerc, extractPercHex, function(x, y){
  newURI <<- str_replace(newURI, 
                         x, 
                         str_c('&#x', y, ';')) 
  })

newURI