从Hash和txt文件在Ruby中创建CSV文件

时间:2016-10-21 22:03:55

标签: ruby file csv hash

我是Ruby的新手。我有一个文件,我想打开创建一个has然后将文件读入一个csv文件。进一步处理。由于某种原因,我无法将哈希中的所有条目都记录到文件中并且正确无误 格式。列格式。

这是示例文件

name: bc0090FB2.st.at.net
address: 192.168.1.2
state: 0
lastpingtime: 2013-02-13
name: bc0110FB2.st.at.net
address: 192.168.1.15
state: 1
lastpingtime: 2013-02-13
name: bc0150FB2.st.at.net
address: 192.168.1.12
state: 2
lastpingtime: 2013-02-13
name: bc0250FB2.st.at.net
address: 192.168.1.5
state: 3
name: bc0560FB2.st.at.net
address: 192.168.1.3
state: 1
lastpingtime: 2013-02-13
name: bc0058FB2.st.at.net
address: 192.168.1.4
state: 2
lastpingtime: 2013-02-13
name: bc0540FB2.st.at.net
address: 192.168.1.10
state: 3
lastpingtime: 2013-02-13
name: bc5890FB2.st.at.net
address: 192.168.1.6
state: 4
name: bc0520FB2.st.at.net
address: 192.168.1.8
state: 2
lastpingtime: 2013-02-13

这是示例代码

require 'csv'

splitup = {}

f = CSV.open("order3.txt", "r") do |fp|
  fp.each do |line|
    # Create a hash to capture each key value pair
    (key, value) =  line.chomp.split(":")
    splitup[key] = value

    namea = splitup["name"]
    addressa = splitup["address"]
    lastping = splitup["lastpingtime"]
    statea = splitup["state"]

    lineA = "#{namea} #{addressa} #{statea} #{lastping}"

    #verifies that the hash works

    puts lineA
  end
end

# trying to put the hash in a csv file 
CSV.open("order25.csv", "w") do |csv|
  csv << ['name', 'address', 'state', 'pingtime']

  splitup.each do |rows|
    csv << rows
  end
end

1 个答案:

答案 0 :(得分:0)

您想要实现的目标尚不清楚,但是,您提供的示例文件没有类似CSV的结构,如果您正确粘贴它,它似乎有一个非常随机的模式。换句话说:nameaddressstatelastpingtime键在原始文本文件中的显示顺序不同。

为了能够将键/值组结构(样本文件)转换为CSV结构,您应该在第一个上有一个标准模式,以便能够以4行为一组读取它,然后将它们合并为一个CSV行。

在ruby中读取文件 n 行,你可以这样:

File.foreach("order3.txt").each_slice(4) do |lines|
  # 'lines' will be an array containing four lines
end