ruby-on-rails - 如何读取包含双引号 (") 的 CSV

标签 ruby-on-rails ruby csv

我有一个如下所示的 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&param=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&param=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&param=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/

相关文章:

python - 如何计算每一行的列数?

Python 正则表达式与 split 方法

postgresql - PostgreSQL 中的 COPY 函数

html - 如何在打印页面时修改表格中的列名?

ruby-on-rails - 关于Ruby中symbol和instance method的一些问题

javascript - 启用 JavaScript 的测试出错(Bootstrap 3、Rails 4、Travis CI)

ruby - 嵌套哈希迭代 : How to iterate a merge over an ( (array of hashes) within a hash )

ruby - 如何使用 Ruby 从文件加载数组?

mysql - 为什么这些线程化的 ActiveRecord 查询不能同时运行?

ruby - 如何使用 Thor (ruby) 创建守护进程?