-1

Below is the text file:

Old count: 56
S id: 1
M id: 1 
New count: 2
Old count: 56
S id: 1
M id: 2
New count: 20
Old count: 56
S id: 1
M id: 2
New count: 32
-----------------------------
Old count: 2
S id: 2
M id: 1
New count: 4
--------------------------------
.
.
.
.

I have used delimiter "---------------" for each ids.

How to parse the value such that the lines with in the delimiter "-----" that is new count is added like this: 2+20+32 = 54

Hash array: count << {'new count' => 54} for first block and so on for remaining blocks.

I have tried like this..

begin
f=File.open("out2", "r")
f.each_line do |line|
@data+=line
end

s_rec=@data.split("------")
s_rec.each do |rec|
row_s=rec.split(/\n/)

row_s.each do |row|

  if r.include?"New count"
    rv=row.split(":")
    @db=rv[1]
  end

  end
  end
4

2 回答 2

1

不确定您要实现的输出格式,但给出了文本:

text = <<__
Old count: 56
S id: 1
M id: 1 
New count: 2
Old count: 56
S id: 1
M id: 2
New count: 20
Old count: 56
S id: 1
M id: 2
New count: 32
-----------------------------
Old count: 2
S id: 2
M id: 1
New count: 4
--------------------------------
.
.
.
.
__

这个:

text
.split(/^-{5,}/)
.map{|s| s.scan(/\bNew count: (\d+)/).map{|match| match.first.to_i}.inject(:+)}

给出:

[
  54,
  4,
  nil
]


在回复评论时,仍然不清楚您想要什么,因为您编写的不是有效的 Ruby 对象,但是:

text
.scan(/^S id: (\d+).+?^New count: (\d+)/m)
.inject(Hash.new(0)){|h, (k, v)| h[k.to_i] += v.to_i; h}
.map{|k, v| {"S id" => k, "new count" => v}}

给出:

[
  {
    "S id"      => 1,
    "new count" => 54
  },
  {
    "S id"      => 2,
    "new count" => 4
  }
]
于 2013-04-20T10:10:57.293 回答
0

我会开始:

data = 'Old count: 56
S id: 1
M id: 1 
New count: 2
Old count: 56
S id: 1
M id: 2
New count: 20
Old count: 56
S id: 1
M id: 2
New count: 32
-----------------------------
Old count: 2
S id: 2
M id: 1
New count: 4
--------------------------------
'

ary = data.split("\n").slice_before(/^---/).map{ |a| a.select{ |s| s['New count:'] }.map{ |s| s[/\d+/].to_i }.inject(:+) }.compact

这给了我一个数组:

[
    [0] 54,
    [1] 4,
]

compact之所以需要,是因为有一个尾随块分隔符,它在发挥它的魔力----时会导致一个空数组。slice_before

从那时起,很容易创建一个哈希数组:

Hash[ ary.map.with_index(1) { |v, i| ["S #{ i }", "new count #{ v }" ] } ]

看起来像:

{
    "S 1" => "新计数 54",
    "S 2" => "新计数 4"
}

分解它,代码通过slice_before返回:

[
    [0] [
        [0]“--------------------------------”,
        [1]“旧计数:56”,
        [2]“S id:1”,
        [3]“中号:1”,
        [4]“新计数:2”,
        [5]“旧计数:56”,
        [6]“S id:1”,
        [ 7]“中号:2”,
        [8]“新计数:20”,
        [9]“旧计数:56”,
        [10]“S id:1”,
        [11]“中号:2”,
        [12]“新计数:32”
    ],
    [1] [
        [0] "-----------------",
        [1]“旧计数:2”,
        [2] "S id: 2",
        [3]“中号:1”,
        [4]“新计数:4”
    ]
]

从那里很简单,选择每个子数组中需要的行,提取值,然后使用inject.

完成后,它只需使用mapwith_index构建字符串和名称/值对,然后Hash将它们转换为哈希。

于 2013-04-20T15:28:48.613 回答