如何从文本文件中拆分数据和拆分日期?

时间:2013-09-06 02:48:24

标签: ruby arrays date csv split

我有一个包含以下数据的CSV数据文件:

id,account_number,balance,date
1,ar161429,482.29,11/28/2007 15:54
2,ar182364,266.93,10/9/2007 15:54
3,ar106644,887.78,10/23/2007 15:54

我正在尝试为日期和帐号创建一个数组,然后将日期进一步分解为日,月和年。我能够根据“,”分割数据,并为帐户和日期创建一个数组,但是当我尝试将日期分为月和日时,它无法正常工作。这是我的代码:

class Account
 puts "Please Enter the name of account file in .txt format"
 balance_file = gets.chomp

 @number_lines = File.read(balance_file).scan(/\n/).count
 @number_lines = @number_lines - 1


 File.open(balance_file) do |aFile|
   @@balance = []
   @@balance_due = []
   @@balance_due_day = []
   @@balance_due_month =[]
   @@balance_due_year = []

   aFile.each_line do |line|
     @@balance << line.split(",").values_at(2)
     @@balance_due << line.split(",").values_at(3)
     puts @@balance_due

   end


   i = 1
   begin
     @@balance_due_day[i] =  @@balance_due[i].split("/").values_at(0)
     @@balance_due_month[i] = @@balance_due[i].slice!(3,2)

     i +=1
   end    while i<@number_lines
 end
end

3 个答案:

答案 0 :(得分:1)

好吧,有很多事要说明:

首先,slice!!结尾,因此大多数爆炸方法都意味着它会更改对象本身而不是仅返回新对象。控制台上的示例:

> a = [1,2,3]
 => [1, 2, 3] 
> a.slice(2,3)
 => [3] 
> a
 => [1, 2, 3] # didn't modified a
> a.slice!(2,3)
 => [3] 
> a
 => [1, 2]  # modified a

其次,不要使用while循环列表。只需使用每个(当然,如果它是多行操作,您可以使用它doend

[1,2,3].each{|x| p x}
1
2
3

第三,前缀为double @的变量不应该是你想象的那样。它们不经常使用。我建议你阅读一下。

要查看日期提取逻辑出了什么问题,最好打开ruby终端(命令为irb)。然后键入一些行,例如

> a_date = a_date.split("/").values_at(0)
 => ["11"] 
> a_date = a_date.slice!(3,2)
 => nil

我没有纠正,因为我不是100%肯定你想要的输出,但我认为你现在可以看到这个问题了。

快乐的黑客攻击

答案 1 :(得分:1)

您应该使用CSV和日期:

require 'csv'
require 'date'

date_and_account_number = []

CSV.foreach('data.csv', :headers => true) do |row|
    date_and_account_number << [row[3],row[1]]
end

date_and_account_number.map! {|e|  dt = DateTime.strptime(e[0],"%m/%d/%Y %H:%M"); [dt.day,dt.month,dt.year,e[1]] }

#=> [[28, 11, 2007, "ar161429"], [9, 10, 2007, "ar182364"], [23, 10, 2007, "ar106644"]]

答案 2 :(得分:0)

string = <<_
id,account_number,balance,date
1,ar161429,482.29,11/28/2007 15:54
2,ar182364,266.93,10/9/2007 15:54
3,ar106644,887.78,10/23/2007 15:54
_

string.sub(/^.*$/, "").scan(%r{^[^,]*,([^,]*),[^,]*,([^/]*)/([^/]*)/(\S*)\s+.*$})
# => [
#      ["ar161429", "11", "28", "2007"],
#      ["ar182364", "10", "9", "2007"],
#      ["ar106644", "10", "23", "2007"]
#    ]