在R中的路径中读取具有UTF-8字符的文件

Read in file with UTF-8 character in path in R

假设我有大量 *.rds 文件,其中一些文件的路径中包含 UTF-8 字符。出于某种原因,R 无法处理某些特殊的重音。例如 enc2utf8("Č"),它应该打印“Č”,但在我这边它转换为“C”,这使得 R 无法识别该文件。关于如何使用编码处理此类 cases/help R 的任何想法?

会话信息输出:

>session.info()
R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)

Matrix products: default

locale:
[1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252    LC_MONETARY=German_Germany.1252
[4] LC_NUMERIC=C                    LC_TIME=German_Germany.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] lubridate_1.7.9 here_0.1        forcats_0.5.0   stringr_1.4.0   dplyr_1.0.2     purrr_0.3.4    
 [7] readr_1.3.1     tidyr_1.1.2     tibble_3.0.3    ggplot2_3.3.2   tidyverse_1.3.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.5       cellranger_1.1.0 pillar_1.4.6     compiler_4.0.2   dbplyr_1.4.4     tools_4.0.2     
 [7] jsonlite_1.7.2   lifecycle_1.0.0  gtable_0.3.0     pkgconfig_2.0.3  rlang_0.4.10     reprex_0.3.0    
[13] cli_2.4.0        DBI_1.1.0        rstudioapi_0.13  haven_2.3.1      withr_2.4.2      xml2_1.3.2      
[19] httr_1.4.2       fs_1.5.0         generics_0.1.0   vctrs_0.3.3      hms_0.5.3        rprojroot_1.3-2 
[25] neuralnet_1.44.2 grid_4.0.2       tidyselect_1.1.0 glue_1.4.2       R6_2.4.1         readxl_1.3.1    
[31] modelr_0.1.8     blob_1.2.1       magrittr_1.5     backports_1.1.9  scales_1.1.1     ellipsis_0.3.1  
[37] rvest_0.3.6      assertthat_0.2.1 colorspace_1.4-1 stringi_1.4.6    munsell_0.5.0    broom_0.7.0     
[43] crayon_1.3.4   

@编辑我:

澄清:由于文件名中的 UTF-8 字符,R 无法读取文件路径。

原始文件路径示例:G:/Users/SomeUser/Documents/University/2021/Project_M/data/procyclingstats/BORA_hansgrohe/POLJAŃSKI_Paweł_sprinter_point.rds

basereadRDSreadr 包的 read_rds 都不能正确编码路径。

两者都会产生以下错误:

Error in gzfile(file, "rb") : cannot open the connection In addition: Warning message: In gzfile(file, "rb") : cannot open compressed file '

G:/Users/SomeUser/Documents/University/2021/Project_M/data/procyclingstats/BORA_hansgrohe/POLJANSKI_Pawel_sprinter_point.rds', probable reason 'No such file or directory

我不使用来源 *.txt 文件加载路径,但有一个函数可以在给定目录中创建文件列表。

此函数正确打印文件路径。所以我连接路径字符串的方式不是问题。

 str_c(outputDIR_pro[i],
                   sub(".+/data/Strava/.+/([0-9]+?).txt", "\1", athlethes[[i]][[j]]) %>% str_match('\d+') %>% 
                    str_detect(names_id_vec,.) %>%
                     names_id_vec[.] %>%
                     str_remove('\d+;'),'_sprinter_point', '.rds') # %>% readRDS
[1] " G:/Users/SomeUser/Documents/University/2021/Project_M/data/procyclingstats/BORA_hansgrohe /POLJAŃSKI_Paweł_sprinter_point.rds"

不确定我是否理解正确。问题出在包含非 ascii 字符的 Rds 文件的文件路径上,还是出在包含非 ascii 字符字符串的 Rds 文件的内容上?

如果问题出在文件路径上,并且您手动将这些 texts/paths 输入到文本文件中,然后通过例如source,问题可能是文本文件没有使用正确的编码保存,在这种情况下,您可以直接使用 unicode 表示法。示例:

cat("\u100")

如果问题出在文件的内容上,并且这些 Rds 文件是在其他地方生成的,并且您确定它们包含正确的文本(例如,如果您尝试 cat(variable) 它显示了应该显示的内容),它们应该与 base R IO 函数一起正常工作,但对于其他包,您可能需要使用 enc2native 转换它们。请注意,并非所有执行 IO 的 CRAN 包都可能支持 windows.

上的非 ascii 字符

到底是什么失败了?

起初我以为是你的区域设置有问题; windows-1252 不包含“Ń”。但是即使使用 latin1 编码和德语语言环境的“.rds”等文件名,我也无法重现您的错误。

但是你的错误中白色space的数量比我为不存在的文件得到的更多......然后我在你的示例输出中发现了领先的space。

[1] " G:/Users/SomeUser/Documents/University/2021/Project_M/data/procyclingstats/BORA_hansgrohe /POLJAŃSKI_Paweł_sprinter_point.rds"

这可以解释为什么它打印“okay”(我们没有看到白色space),但尝试读取会失败。这确实让我感到困惑,为什么您的其他文件读取没有问题。

如果这不是问题,那可能是 Windows 中最近对 utf-8 的支持。从历史上看,他们在内部使用 ucs-2 和 utf-16。 “打开”utf-8 支持需要不同的 C 运行时。有一个 experimental build 的 R,您可以尝试使用该运行时。但这也需要您使用该运行时重建您的库(readr!)。

在搞砸你的整个 R 安装之前,我会用实验版本测试你是否可以读取名为 Ń.csv.

的文件

我想我找到了原始问题的解决方案,尽管我不完全理解为什么这个解决方案有效。我在 Windows 10(64 位)上使用 R 版本 3.6.1,区域设置为“English_United States.1252”。

readRDSunicode <- function(filename) {
  stopifnot(is.character(filename), Encoding(filename) == "UTF-8")
  z <- file(filename, open = "rb")
  conn <- gzcon(z)
  readRDS(conn)
}

filename <- "POLJA\U0143SKI_Pawe\U0142_sprinter_point.rds"
setwd("C:/Users/Public/Documents/R Working Directory/test unicode in filenames")
xx <- readRDSunicode(filename)

诀窍是使用 gzcon 而不是 gzfile。我从 manual page UTF8filepaths 得到的,我认为这可能是 R 版本 4 中的新内容。该页面的“Windows”部分指出 gzfile(和其他一些函数)无法访问不在当前编码中。该页面继续说,“对于使用 gzfile 的函数(包括 load、readRDS、read.dcf 和 tar),通常可以使用包装文件连接的 gzcon 连接。”

此外,指定文件名时需要使用\U 表示法。如果你输入 filename <- "POLJAŃSKI_Paweł_sprinter_point.rds" 它不起作用(我假设如果你的语言环境是波兰语, 工作。)为了获得特殊字符的十六进制代码,我去了 Richard Tobin's UTF-8 conversion tool.

a question from 2014 that raises a similar issue 个 Windows 个文件名的字符不在本机编码中。那里的答案有一些有用的提示,例如使用函数 Sys.glob(paths="*") 而不是 dir().

我讨论了一个相关问题,关于在 Windows、here.

中使用 R 中的特殊字符

关于 Windows 中 R 中 UTF-8 编码字符串处理的各种错误报告已提交,包括 11515, 14271, 15762, 16064, 16101, and 16232.