使用UTF-8编译错误

时间:2016-06-16 19:05:29

标签: r encoding utf-8 rvest

我正试图从维基百科中获取this表。该文件的来源是它的UTF-8:

> <!DOCTYPE html> <html lang="en" dir="ltr" class="client-nojs"> <head>
> <meta charset="UTF-8"/> <title>List of cities in Colombia - Wikipedia,
> the free encyclopedia</title>
> ...

但是,当我尝试使用rvest获取表时,它会显示奇怪的字符,其中应该有重音(标准西班牙语),如á,é等。 这就是我的尝试:

theurl <- "https://en.wikipedia.org/wiki/List_of_cities_in_Colombia"
file <- read_html(theurl, encoding = "UTF-8")
tables <- html_nodes(file, "table")
pop <- html_table(tables[[2]])
head(pop)

##   No.         City Population         Department
## 1   1      Bogotá  6.840.116       Cundinamarca
## 2   2    Medellín  2.214.494          Antioquia
## 3   3         Cali  2.119.908    Valle del Cauca
## 4   4 Barranquilla  1.146.359         Atlántico
## 5   5    Cartagena    892.545           Bolívar
## 6   6      Cúcuta    587.676 Norte de Santander

我试图按照其他SO问题的建议修复编码:

repair_encoding(pop)

## Best guess: UTF-8 (100% confident)
## Error in stringi::stri_conv(x, from = from) : 
##   all elements in `str` should be a raw vectors

我测试了几种不同的编码(latin1,以及guess_encoding()提供的其他编码,但所有这些编码产生了类似的错误结果。

如何正确加载此表?

1 个答案:

答案 0 :(得分:3)

看起来你必须在字符向量上使用repair_encoding,而不是整个数据帧......

> repair_encoding(head(pop[,2]))
Best guess: UTF-8 (80% confident)
[1] "Bogotá"       "Medellín"     "Cali"         "Barranquilla"
[5] "Cartagena"    "Cúcuta"