csv - 当字符串以\结尾时 readtable()

标签 csv julia

当我读入包含以下内容的 csv 文件时

"number","text"

1,"row1text\"

2,"row2text"

使用命令

using DataFrames

readtable(filename.csv)

我得到一个只有一行的数据框。显然,第一行文本末尾的反斜杠有问题。这是预期的行为吗?有没有其他方法可以避免这个问题?

作为旁注:以下内容工作正常(即我得到两行),但对于读取大文件显然不切实际

    df = csv"""

    "number","text"

    1,"row1text\"

    2,"row2text"

    """

最佳答案

由于反斜杠默认是转义字符,它会转义引号并弄乱一切。一种解决方法是使用 CSV.jl 包并指定不同的转义字符:

julia>  using CSV

julia> CSV.read("filename.csv", escapechar = '~')
2×2 DataFrames.DataFrame
│ Row │ number │ text        │
├─────┼────────┼─────────────┤
│ 1   │ 1      │ "row1text\" │
│ 2   │ 2      │ "row2text"  │

但是你必须确保 ~ 字符没有转义其他内容。可能有更好的方法来做到这一点,但这将是解决该问题的一种技巧。

另一种方法是逐行处理数据。这是一个过于复杂的示例:

julia> open("filename.csv", "r") do f
           for (i, line) in enumerate(eachline(f))
               if i == 1
                 colnames = map(Symbol, split(line, ','))

                 global df = DataFrame(String, 0, length(colnames))

                 rename!(df,
                       Dict([(old_name, new_name) for (old_name, new_name) in zip(names(df), colnames)]))

               else
                   new_row = map(String, split(replace(line, "\\\"", "\""), ','))
                   # replace quotes around vales
                   new_row = map(x -> replace(x, "\"", ""), new_row)
                   push!(df, new_row)
               end
           end
       end

julia> df
2×2 DataFrames.DataFrame
│ Row │ "number" │ "text"     │
├─────┼──────────┼────────────┤
│ 1   │ "1"      │ "row1text" │
│ 2   │ "2"      │ "row2text" │

关于csv - 当字符串以\结尾时 readtable(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754115/

相关文章:

python - 在 python 中的 CSV 文件的 2 列中写入 2 个列表

.net - 使用 LinqToCSV - 忽略额外的列?

database - 如何在 Julia 中实现 One-Vs-Rest 多类分类?

Julia 函数返回匿名函数

julia - for循环中的多个条件?

fortran - 使用 Julia 编译 Fortran77

julia - 如何在 Julia 中处理分类数据?

java - 如何将 StringBuilder 中的所有信息数据(文本)插入 .csv 文件中的一行

java - 如何在不创建新文件的情况下更新文件

python - 使用 Python 将列添加到现有的 CSV 文件