[英]Ruby parsing CSV rows in a loop
我正在嘗試編寫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"]
您需要使用數組數組來存儲結果,而您正在使用單個數組,因此您已經提到了輸出。
在循環內移動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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.