代码之家  ›  专栏  ›  技术社区  ›  rane

如何在fwrite()中指定用于导出csv文件的encode?

  •  1
  • rane  · 技术社区  · 6 年前

    fwrite() ,如何以最快的速度导出特定编码的csv文件 写入() 写入()

    fwrite(DT,"DT.csv",encoding = "UTF-8")
    Error in fwrite(DT, "DT.csv", encoding = "UTF-8") : 
      unused argument (encoding = "UTF-8")
    
    1 回复  |  直到 6 年前
        1
  •  6
  •   user2554330    4 年前

    你应该张贴一个可复制的例子,但我想你可以做到这一点,确保数据中 DT

    例如,

    DF <- data.frame(text = "á", stringsAsFactors = FALSE)
    DF$text <- enc2utf8(DF$text) # Only necessary if Encoding(DF$text) isn't "UTF-8"
    Encoding(DF$text) <- "unknown"
    data.table::fwrite(DF, "DF.csv", bom = TRUE)
    

    如果 DF 如果是因子,则需要将它们转换为字符向量,然后才能工作。

        2
  •  4
  •   SirTain    5 年前

    在编写本文时,fwrite不支持强制编码。我使用了一种变通方法,但它比我想要的要迟钝一些。举个例子:

    readr::write_excel_csv(DT[,0],"DT.csv")
    data.table::fwrite(DT,file = "DT.csv",append = T)
    

    第一行将只将数据表的标题保存到CSV,默认为UTF-8,并带有字节顺序标记,以便让Excel知道文件是UTF-8编码的。这个 写入文件 语句然后使用append选项向原始CSV添加其他行。这将保留 ,同时最大化写入速度。

        3
  •  2
  •   s_baldur    4 年前


    尝试以下工作方法:

    # You have DT   
    # DT is a data.table / data.frame   
    # DT$text contains any text data not encoded with 'utf-8'       
    
    library(data.table)   
    DT$text <– enc2utf8(DT$text) # it forces underlying data to be encoded with 'utf-8'   
    fwrite(DT, "DT.csv", bom = T) # Then save the file using ' bom = TRUE ' 
    

    希望有帮助。

        4
  •  1
  •   cach dies    4 年前

    # Encode data in UTF-8
    for (col in colnames(DT)) {
        names(DT) <- enc2utf8(names(DT)) # Column names need to be encoded too
        DT[[col]] <- as.character(DT[[col]]) # Allows for enc2utf8() and Encoding()
        DT[[col]] <- enc2utf8(DT[[col]]) # same as users' answer
        Encoding(DT[[col]]) <- "unknown"
    }
    
    fwrite(DT, "DT.csv", bom = T)
    
    # When re-importing your data be sure to use encoding = "UTF-8"
    DT2 <- fread("DT.csv", encoding = "UTF-8") 
    # DT2 should be identical to the original DT
    

    这应该适用于data.table中任意位置的所有UTF-8字符