R中使用rvest库解析UTF-8编码时出现了编码错误

4

我正在尝试从维基百科获取表格。该文件的来源声称它是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个回答

3

看起来你需要在字符向量上使用repair_encoding,而不是整个数据框...

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接