代码之家  ›  专栏  ›  技术社区  ›  Max Williams

如何在Ruby中拆分CSV字符串?

  •  3
  • Max Williams  · 技术社区  · 15 年前

    我有一个CSV文件的例子:

    2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"
    

    我想把它分成一个数组。现在的想法是直接在逗号上拆分,但是有些字符串中有逗号,例如“生命和生活过程,生命过程”,这些字符串应该作为数组中的单个元素保留。还要注意两个逗号之间没有任何内容-我想把它们作为空字符串。

    换句话说,我想得到的数组是

    [2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes","","",1,0,"endofline"]
    

    我可以想到一些涉及eval的老套方法,但我希望有人能想出一个干净的regex来做这件事。。。

    干杯,麦克斯

    5 回复  |  直到 15 年前
        1
  •  3
  •   steenslag    15 年前
    str=<<EOF
    2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"
    EOF
    require 'csv' # built in
    
    p CSV.parse(str)
    # That's it! However, empty fields appear as nil.
    # Makes sense to me, but if you insist on empty strings then do something like:
    parser = CSV.new(str)
    parser.convert{|field| field.nil? ? "" : field}
    p parser.readlines
    
        2
  •  9
  •   user229044    15 年前

    这不是正则表达式的合适任务。你 需要 一个CSV解析器,Ruby内置了一个:

    http://ruby-doc.org/stdlib/libdoc/csv/rdoc/classes/CSV.html

    还有一个可以说是一流的第三部分库:

    http://fastercsv.rubyforge.org/

        3
  •  2
  •   Dave    15 年前

    编辑:我未能读取Ruby标记。好消息是,即使语言细节不对,指南也会解释构建这个模型的理论。对不起的。

    这里有一个很棒的指南:

    http://knab.ws/blog/index.php?/archives/10-CSV-file-parser-and-writer-in-C-Part-2.html

    csv编写器在这里:

    http://knab.ws/blog/index.php?/archives/3-CSV-file-parser-and-writer-in-C-Part-1.html

    这些例子涵盖了csv中有一个带引号的文本(可能包含也可能不包含逗号)的情况。

        4
  •  2
  •   ghostdog74    15 年前
    text=<<EOF
    2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"
    EOF
    x=[]
    text.chomp.split("\042").each_with_index do |y,i|
      i%2==0 ?  x<< y.split(",") : x<<y
    end
    print x.flatten
    

    $ ruby test.rb
    ["2412", "21", "Which of the following is not found in all cells?", "Curriculum", "Life and Living Processes, Life Processes", "", "", "", "1", "0", "endofline"]
    
        5
  •  1
  •   poseid    15 年前

    今天早上,我偶然发现了Ruby on Rails的CSV表导入器项目。最终您会发现代码很有用:

    Github TableImporter