通过SPARQL使用R XML编码问题 [英] Encoding problems with R XML via SPARQL
问题描述
我遇到了R的SPARQL软件包的编码问题.我正在运行以下代码:
I running into an encoding problem with the SPARQL package for R. I'm running the following code:
library(SPARQL)
rights_query <- '
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX edm: <http://www.europeana.eu/schemas/edm/>
PREFIX ore: <http://www.openarchives.org/ore/terms/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT DISTINCT ?edmrights ?provider (COUNT(*) as ?count)
WHERE {
?agg rdf:type ore:Aggregation .
?agg edm:rights ?edmrights .
#?agg dc:rights ?dcrights .
?agg edm:dataProvider ?provider .
?proxy ore:proxyIn ?agg .
?proxy edm:type "IMAGE" .
}
GROUP BY ?edmrights ?provider
ORDER BY ?provider DESC(?count)'
eur <- "http://europeana.ontotext.com/sparql"
eur_data <- SPARQL(eur, rights_query)$results
write.csv(eur_data, "results.csv")
代码运行时没有任何错误或警告,但是在RStudio和CSV中查看的结果数据帧显然存在编码问题.
The code runs without any errors or warnings, however the resulting data frame as viewed in RStudio, as well as the CSV, clearly have encoding problems.
例如,最后一个应该部分是西里尔字母:Чувашский государственный художественный музей / Chouvashia State Art Museum
For example, the last ought to be partly Cyrillic: Чувашский государственный художественный музей / Chouvashia State Art Museum
但是结果如下:ЧÑваÑÑкий гоÑÑдаÑÑÑвеннÑй ÑÑдожеÑÑвеннÑй мÑзей / Chouvashia State Art Museum
我已经检查了SPARQL查询返回的XML.它通过XML验证,并包含正确的"UTF-8"编码声明. R XML包(R SPARQL包用来将XML输出解析为数据帧的方式)应该认识到这一点,对吧?
I've inspected the XML returned by the SPARQL query. It passes XML validation, and contains the proper "UTF-8" encoding declaration. The R XML package (which is what the R SPARQL package uses to parse XML output into a data frame) ought to recognize this, right?
您可以检查整个 XML输出,以及 CSV文件.我正在OS X Mavericks上通过RStudio运行R 3.1.0.我已将RStudio的默认字符编码设置为UTF-8.
You can inspect the entire XML output, as well as the CSV file. I am running R 3.1.0 via RStudio, on OS X Mavericks. I have set RStudio's default character encoding to UTF-8.
推荐答案
而不是SPARQL.R,我将考虑以下内容: ...
instead of SPARQL.R in this case I would consider something like the following: ...
Sys.setenv(LANG="ru")
library(RCurl)
library(XML)
url=<SPARQL endpoint query URL>
xquery=<your query which may contain windows-1251 chars on Windows 7+>
#xquery=iconv(xquery,"CP1251","UTF-8") #it may be required on Windows 7+
param="query"
extrastr=""
resp <- getURL(url = paste(url, '?', param, '=', gsub('\\+','%2B',URLencode(xquery,reserved=TRUE)), extrastr, sep=""), httpheader = c(Accept="application/sparql-results+xml"),.encoding="UTF-8")
xmlResp=xmlParse(resp)
xmlRespRoot=xmlRoot(xmlResp)
nRows=xmlSize(xmlRespRoot[2]$results)
if (nRows>0){
xRespList=NULL
for(i in 1:nRows){
xrow=NULL
tmprow=(xmlRespRoot[2]$results)[i]$result
nCols=xmlSize(tmprow)
for(j in 1:nCols){
xrow=cbind(xrow,xmlValue(tmprow[j]$binding,encoding="UTF-8"))
}
xRespList=rbind(xRespList,xrow)
}
}
这篇关于通过SPARQL使用R XML编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!