【问题标题】:Ruby - comparing adjacent entries in one column of a csv fileRuby - 比较 csv 文件的一列中的相邻条目
【发布时间】:2023-03-16 06:13:01
【问题描述】:

我是 Ruby 的新手,如果这太容易了,我深表歉意 :-)

我有一个包含 5 列的 .csv 文件。第一列有一个记录标识符(在这种情况下是驱动程序编号),每行中的其他 4 列有与该记录相关的数据。对于每条记录,大约有 50 行数据(总共不到 2,000 行)。 .csv 文件有一个标题行。

我需要阅读 .csv 文件并确定每个用户的最后一个条目,这样我才能继续处理下一个用户。我试图让它比较第一列和下一行中的条目。

到目前为止,我有这个,它返回不正确的行号,它们在 1 到 5 行之间...?!?!

require 'csv-mapper'

  Given(/^I compare the driver numbers from rows "(.*?)" to "(.*?)"$/) do |firstrow, lastrow|
    data = CsvMapper.import('C:/auto_test_data/Courts code example csv.csv', headers: true) do
      [dln]
    end

    row = firstrow.to_i
    while row <= lastrow.to_i
      @licnum1 = data.at(row).dln
      @licnum2 = data.at(row+1).dln

      if
        @licnum2 == @licnum1
          $newrecord = "same"
      else
        $newrecord = @licnum2
      end

      if   
        $newrecord != "same"
        puts "Last row for #{@licnum1} is #{row}\n"
      end

      row = row + 1
    end
  end

这是 .csv 文件的布局:

recordidentifier1   dataitem1   dataitem2 code descriptionforcomparison
recordidentifier1   dataitem1   dataitem2 code descriptionforcomparison
recordidentifier2   dataitem1   dataitem2 code descriptionforcomparison
recordidentifier2   dataitem1   dataitem2 code descriptionforcomparison

我们将不胜感激所有帮助。

谢谢,

彼得

【问题讨论】:

    标签: ruby csv


    【解决方案1】:

    这是一种方法

    current_identifier = nil
    
    (firstrow.to_i..lastrow.to_i).each do |row|
    
      if current_identifer != data.at(row).dln # current row is new identifier
        if current_identifier # this is not the first row
           puts "Last row for #{current_identifier} is #{row-1}\n"
        end
        current_identifier = data.at(row).dln # remember current row
      end
    
      # we need to track the last row as the last for the current identifier
      puts "Last row for #{current_identifier} is #{lastrow.to_i}\n" 
    

    【讨论】:

    • 谢谢,先生们 :-) 为整理问题干杯,@peter。
    • 我终于到了。
    猜你喜欢
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2012-09-26
    相关资源
    最近更新 更多