You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UTF-8环境下R解压拉丁编码文件及CRAN包访问归档问题

解决UTF-8环境下R解压拉丁编码Zip文件的问题

问题解答

  1. 能在UTF-8区域设置的R环境中解压拉丁编码文件,但需要先转换Zip包内文件名的编码,避免因编码不匹配导致的非法字节序列错误。
  2. 有简便方法仅用R和CRAN包访问归档内容,核心思路是先读取并转换文件名编码,再提取并重命名文件。

问题原因

你遇到的报错是因为Zip归档中的文件名使用了拉丁编码(如ISO-8859-1),而macOS GitHub Action环境默认采用UTF-8 locale,系统无法识别编码不匹配的文件名,导致创建文件失败。例如报错中的Cadastro de Locais de Aquisi<87><c6>o.xls,实际是拉丁编码的Cadastro de Locais de Aquisição.xls。

解决方案代码

方法一:使用archive包处理

library(archive)

# 下载归档文件
dictionary_tf <- tempfile()
dictionary_url <- paste0(
    "https://ftp.ibge.gov.br/Orcamentos_Familiares/" ,
    "Pesquisa_de_Orcamentos_Familiares_2017_2018/Microdados/Documentacao_20230713.zip"
)
download.file(dictionary_url, dictionary_tf, mode = 'wb')

# 获取归档内文件列表,转换文件名编码(从ISO-8859-1转UTF-8)
zip_file_list <- archive(dictionary_tf)
zip_file_list$path <- iconv(zip_file_list$path, from = "ISO-8859-1", to = "UTF-8")

# 创建输出目录
output_dir <- tempdir()

# 逐个提取并正确命名文件
for (idx in seq(nrow(zip_file_list))) {
    target_file <- zip_file_list$path[idx]
    # 提取到临时路径
    archive_extract(dictionary_tf, files = target_file, dir = tempdir())
    # 重命名为UTF-8编码的文件名
    file.rename(
        file.path(tempdir(), target_file),
        file.path(output_dir, target_file)
    )
}

方法二:使用基础包utils的unzip函数

library(utils)

# 下载归档文件
dictionary_tf <- tempfile()
dictionary_url <- paste0(
    "https://ftp.ibge.gov.br/Orcamentos_Familiares/" ,
    "Pesquisa_de_Orcamentos_Familiares_2017_2018/Microdados/Documentacao_20230713.zip"
)
download.file(dictionary_url, dictionary_tf, mode = 'wb')

# 获取文件名列表并转换编码
zip_list <- unzip(dictionary_tf, list = TRUE)
zip_list$Name <- iconv(zip_list$Name, from = "ISO-8859-1", to = "UTF-8")

output_dir <- tempdir()

# 解压所有文件
unzip(dictionary_tf, exdir = output_dir, junkpaths = TRUE)

# 重命名文件(处理目录结构)
for (idx in seq(nrow(zip_list))) {
    old_path <- file.path(output_dir, basename(zip_list$Name[idx]))
    new_path <- file.path(output_dir, zip_list$Name[idx])
    # 创建必要的子目录
    dir.create(dirname(new_path), recursive = TRUE, showWarnings = FALSE)
    file.rename(old_path, new_path)
}

注意事项

  • 如果ISO-8859-1编码转换无效,可以尝试Windows-1252,这是另一种常见的拉丁编码。
  • 处理带有子目录的归档时,方法二需要额外创建对应目录,确保文件路径正确。

内容的提问来源于stack exchange,提问作者Anthony Damico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:40:37