本文介绍了文本的多级解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上次我遇到问题时:Parsing and structuring of a text file现在我想象复杂的情况。例如。我有一个包含NEXT CONTAINT的文本文件:

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

当我使用此方法时,我得到一个没有NUM值的字符串。

是否执行我的任务意味着"在可能的情况下"?

推荐答案

each挡路中声明的变量在两次迭代之间不会持久化。当迭代结束时,这些变量就消失了,这就是为什么您会丢失以前的sub值。要修复它,请将sub变量移到外部作用域,方法是在each之前对其进行初始化,就像您对current_head

所做的那样
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

在repl.it上查看:https://repl.it/GBKn

这篇关于文本的多级解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 15:05