我最後一次遇到問題: Parsing and structuring of a text file 現在我想象一下複雜的情況。例如, 。我有一個包含下一個文本文件:多級解析文本
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值的字符串。
是否執行我的任務意味着「case when」可能?
謝謝您的解決方案! – Misha1991