MAC 上的编码问题
Encoding problems on MAC
我正在尝试下载一个文件并加载到 R 中,但它不起作用。
我在 MAC,使用 R 3.1.3
文件为csv格式(还有json格式选项)。
这是文件的 url(csv 和 json):
http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv
http://dadosabertos.dataprev.gov.br/opendata/con02/formato=json
我知道我可以下载文件,在本地文本编辑器中打开,另存为 utf-8,然后导入到 R。但我想要一个更自动化的解决方案,不涉及使用其他软件.而且,顺便说一句,即使是这个解决方案也不像我预期的那样简单。
这是我到目前为止尝试过的:
由于文件是葡萄牙语,我知道它可能是 utf-8。
library(jsonlite)
options(encoding = "utf-8")
url <- "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=json"
prev <- fromJSON(url)
错误信息:
词法错误:UTF8 字符串中的字节无效。
:[{"node":{"Ano":"1988","Esp�cie":"42-Ap Tempo 贡献
(就在这里)------^
我也试过了
url1 <- "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv"
上一个 <- read.csv(url, sep=",")
但是也没用。我也尝试使用:
Sys.setlocale("LC_ALL", 'en_US.UTF-8')
但没有任何区别。
至少 csv 版本似乎是 ISO-8859-1 而不是 UTF-8。您可以使用 curl
命令来检查内容类型,如下所示:
$ curl -I "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv"
HTTP/1.1 200 OK
Set-Cookie: ACE_STICKY=R835601189; path=/; expires=Thu, 19-May-2016 00:43:56 GMT
Server: nginx/1.2.4
Date: Wed, 18 May 2016 00:27:45 GMT
Content-Type: text/plain; charset=ISO-8859-1
Connection: keep-alive
X-Powered-By: PHP/5.3.3
Content-Disposition: attachment; filename="CON02.csv";
Access-Control-Allow-Origin: *
从内容来看,这似乎是正确的。我不熟悉 r 的编码选项,但尝试设置 `options(encoding = "ISO-8859-1") 看看会发生什么。
我是这样解决的:
url<-"http://dadosabertos.dataprev.gov.br/opendata/act10/formato=json"
a<-readLines(file(url, encoding="ISO-8859-1"), warn=FALSE)
prev<-fromJSON(a)
我正在尝试下载一个文件并加载到 R 中,但它不起作用。 我在 MAC,使用 R 3.1.3
文件为csv格式(还有json格式选项)。
这是文件的 url(csv 和 json): http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv http://dadosabertos.dataprev.gov.br/opendata/con02/formato=json
我知道我可以下载文件,在本地文本编辑器中打开,另存为 utf-8,然后导入到 R。但我想要一个更自动化的解决方案,不涉及使用其他软件.而且,顺便说一句,即使是这个解决方案也不像我预期的那样简单。
这是我到目前为止尝试过的: 由于文件是葡萄牙语,我知道它可能是 utf-8。
library(jsonlite)
options(encoding = "utf-8")
url <- "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=json"
prev <- fromJSON(url)
错误信息:
词法错误:UTF8 字符串中的字节无效。 :[{"node":{"Ano":"1988","Esp�cie":"42-Ap Tempo 贡献 (就在这里)------^
我也试过了 url1 <- "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv" 上一个 <- read.csv(url, sep=",")
但是也没用。我也尝试使用:
Sys.setlocale("LC_ALL", 'en_US.UTF-8')
但没有任何区别。
至少 csv 版本似乎是 ISO-8859-1 而不是 UTF-8。您可以使用 curl
命令来检查内容类型,如下所示:
$ curl -I "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv"
HTTP/1.1 200 OK
Set-Cookie: ACE_STICKY=R835601189; path=/; expires=Thu, 19-May-2016 00:43:56 GMT
Server: nginx/1.2.4
Date: Wed, 18 May 2016 00:27:45 GMT
Content-Type: text/plain; charset=ISO-8859-1
Connection: keep-alive
X-Powered-By: PHP/5.3.3
Content-Disposition: attachment; filename="CON02.csv";
Access-Control-Allow-Origin: *
从内容来看,这似乎是正确的。我不熟悉 r 的编码选项,但尝试设置 `options(encoding = "ISO-8859-1") 看看会发生什么。
我是这样解决的:
url<-"http://dadosabertos.dataprev.gov.br/opendata/act10/formato=json"
a<-readLines(file(url, encoding="ISO-8859-1"), warn=FALSE)
prev<-fromJSON(a)