由於反斜槓是默認轉義字符閱讀,它避開報價標記和攪亂一切。一個解決辦法是使用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_str中使用的IOBuffer(轉義)造成的。雖然你喜歡這種行爲,但它可能是bug。 – Liso