【问题标题】:Ruby parsing CSV rows in a loopRuby 在循环中解析 CSV 行
【发布时间】:2015-10-08 16:56:29
【问题描述】:

我正在尝试编写一个 CSV 解析器。每行都有多个我需要处理的字段。每条线代表患者数据,所以我需要每条线自己处理。处理完每一行后,我需要转到下一行,直到到达文件末尾。

我已经成功开始用 Ruby 编写解析器。数据正在被导入,它正在创建一个数组数组(每一行都是一个数组)。

我遇到的问题是逐行正确循环数据。所以,现在我可以成功处理第一行并解析每个字段。当我添加另一行新患者数据时,我开始遇到问题。第二行被处理并添加到已创建的新数组中。例如,第 1 行和第 2 行一旦处理,就被添加到一个大数组而不是数组数组中。导入的数据需要以相同的结构输出。

到目前为止,这是我的代码:

original_data = Array.new
converted_data = Array.new

Dir.chdir 'convert'
CSV.foreach('CAREPRODEMO.CSV') do |raw_file|
  original_data << raw_file
end

# Needed at beginning of array for each patient
converted_data.insert(0, 'Acvite', 'ACT')

# Start processing fields
original_data.each do |o|

  # BEGIN Check for nil in original data and replace with empty string
  o.map! { |x| x ? x : ''}

  converted_data << o.slice(0)

  # Remove leading zeros from account number
  converted_data[2].slice!(0)
  if converted_data[2].slice(1) == '0'
    converted_data[2].slice!(1)
  end

  # Setup patient name to be processed
  patient_name = Array.new

  patient_name << o.slice(3..4)
  converted_data << patient_name.join(' ')

  # Setup patient address to be processed
  patient_address = Array.new

  patient_address << o.slice(5)
  converted_data << patient_address.join(' ')



  # END Check for nil in converted data and replace with empty string
  converted_data.map! { |x| x ? x : ''}

end

# For debugging
p converted_data

输出:

["Acvite", "ACT", "D65188596", "SILLS DALTON H", "16243 B L RD", "00D015188596", "BALLARD DAVE H", "243 H L RD", "", "", ""]

通缉:

["Acvite", "ACT", "D65188596", "SILLS DALTON H", "16243 B L RD"]
["Acvite", "ACT", "D15188596", "BALLARD DAVE H", "243 H L RD"]

【问题讨论】:

    标签: arrays ruby parsing csv


    【解决方案1】:

    您需要使用数组数组来存储结果,您使用的是单个数组,因此您提到了输出。

    在循环内移动converted_data数组,并定义一个新数组来收集每个循环的输出。一种可能的方法如下所示。

    original_data = Array.new
    
    # Changed the variable name from converted_data
    final_data = Array.new 
    ...
    original_data.each do |o|
       converted_data = Array.new
       ...
    
       # END Check for nil in converted data and replace with empty string
       converted_data.map! { |x| x ? x : ''}
    
       final_data << converted_data
    end
    
    p final_data
    

    【讨论】:

    • 谢谢。这完全符合我的需要。必须修改代码以确保到达行尾后不会在末尾插入空数组。
    猜你喜欢
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多