Ruby 多级解析文本

Ruby 多级解析文本,ruby,parsing,case-when,Ruby,Parsing,Case When,上次我遇到问题时: 现在我想象复杂的情况。 例如我有一个包含以下内容的文本文件: Head 1 Subhead 1 a 10 b 14 c 88 Subhead 2 a 15 b 16 c 17 d 88 Subhead 3 a 55 b 36 c 87 Head 4 Subhead 1 r 32 t 55 s 79 r 22 t 88 y 53 o 78 p 90 m 44 Head 53 Subtitle 1 y 22 b 33 Subtitle 2 a 88 g 43 r 87 Head

上次我遇到问题时: 现在我想象复杂的情况。 例如我有一个包含以下内容的文本文件:

Head 1
Subhead 1
a 10
b 14
c 88
Subhead 2
a 15
b 16
c 17
d 88
Subhead 3
a 55
b 36
c 87
Head 4
Subhead 1
r 32
t 55
s 79
r 22
t 88
y 53
o 78
p 90
m 44
Head 53
Subtitle 1
y 22
b 33
Subtitle 2
a 88
g 43
r 87
Head 33
Subhead 1 
z 11
d 66
v 88
b 69
Head 32
Subhead 1
n 88
m 89
b 88
Subhead 2
b 88
m 43
现在我需要结构文本到下一个平面。我想获得下一个数据:

Head 1, Subhead 1, c 88
Head 1, Subhead 2, d 88
Head 4, Subhead 1, t 88
Head 53, Subhead 2, a 88
Head 33, Subhead 1, v 88
Head 32, Subhead 1, n 88
Head 32, Subhead 1, b 88
Head 32, Subhead 2, b 88
也就是说,我想得到所有行,其中88表示标题和分标题

我的行动:

lines = File.open("file.txt").to_a
lines.map!(&:chomp) # remove line breaks

current_head = ""
res = []

lines.each do |line|
  case line
  when /Head \d+/
    current_head = line
  when /Subhead/
    sub = line
  when /\w{1} 88/
  num = line
    res << "#{current_head}, #{sub}, #{num}"
  end
end

puts res
lines=File.open(“File.txt”)。到
线,地图!(&:chomp)#删除换行符
当前_头=“”
res=[]
行。每个do |行|
箱线
何时/Head\d+/
电流头=线
何时/分目/
子=行
当/\w{1}88/
num=行

res在
每个
块中声明的变量在迭代之间不会保持不变。当迭代结束时,这些变量消失,这就是为什么您会丢失上一个
sub
值。要修复它,请将
sub
变量移动到外部作用域,方法是在
每个
之前对其进行初始化,就像使用
当前头
一样:

current_head = ""
current_sub = ""
res = []

lines.each do |line|
  case line
  when /Head \d+/
    current_head = line
  when /Subhead/
    current_sub = line
  when /\w{1} 88/
  num = line
    res << "#{current_head}, #{current_sub}, #{num}"
  end
end
current_head=“”
当前_sub=“”
res=[]
行。每个do |行|
箱线
何时/Head\d+/
电流头=线
何时/分目/
当前_子=线路
当/\w{1}88/
num=行

res如果希望在两次迭代之间保持变量,可以使用实例变量

File.foreach
是读取文件的推荐方式:

res = []
File.foreach("file.txt") do |line|
  line.chomp!
  case line
  when /Head \d+/
    @current_head = line
  when /Sub(head|title)/
    @sub = line
  when /\w 88/
    num = line
    res << "#{@current_head}, #{@sub}, #{num}"
  end
end
puts res
res=[]
File.foreach(“File.txt”)do |行|
line.chomp!
箱线
何时/Head\d+/
@电流头=线
当/分(标题|标题)/
@子=行
何时/\w 88/
num=行

谢谢你的解决方案!foreach真的很方便谢谢你的解决方案!