我有一个如下所示的 CSV 文件
"url","id","role","url","deadline","availability","location","my_type","keywords","source","external_id","area","area (1)"
"https://myurl.com","123456","This a string","https://myurl.com?source=5¶m=1","31-01-2020","1","Location´s Place","another_string, my_string","key1, key2, key3","anotherString","145129","Place in Earth",""
它有 13 列。
问题是我得到的每一行都带有\",但我不希望这样。此外,我在读取中返回了 16 列。
这就是我所做的
csv = CSV.new(File.open('myfile.csv'), quote_char:"\x00", force_quotes:false)
csv.read[1]
Output:
["\"https://myurl.com\"", "\"123456\"", "\"This a string\"", "\"https://myurl.com?source=5¶m=1\"", "\"31-01-2020\"", "\"1\"", "\"Location´s Place\"", "\"another_string", " my_string\"", "\"key1", " key2", " key3\"", "\"anotherString\"", "\"145129\"", "\"Place in Earth\"", "\"\""]
最佳答案
您显示的文件是标准 CSV 文件。没有什么特别需要的。只需删除所有不必要的参数即可:
csv = CSV.new(File.open('myfile.csv'))
csv.read[1]
#=> [
# "https://myurl.com",
# "123456",
# "This a string",
# "https://myurl.com?source=5¶m=1",
# "31-01-2020",
# "1",
# "Location´s Place",
# "another_string, my_string",
# "key1, key2, key3",
# "anotherString",
# "145129",
# "Place in Earth",
# ""
# ]
force_quotes
不会在您的代码中执行任何操作,因为它控制 CSV 库在写入 CSV 时是否引用所有字段。你是在读,不是在写,所以这个论证是没有用的。quote_char: "\x00"
显然错误,因为您发布的示例中的引号字符显然是"
而不是NUL
。quote_char: '"'
是正确的,但不是必需的,因为它是默认值。
关于ruby-on-rails - 如何读取包含双引号 (") 的 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214785/