当我读入包含以下内容的 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/