文本文件的解析和结构化 [英] Parsing and structuring of a text file

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

问题描述

我需要帮助,并且使用Ruby.我有一个包含以下内容的文本文件:

I need help and I use Ruby. I had a text file with next contain:

Head 1
a 10
b 14
c 15
d 16
e 17
f 88
Head 4
r 32
t 55
s 79
r 22
t 88
y 53
o 78
p 90
m 44
Head 53
y 22
b 33
Head 33
z 11
d 66
v 88
b 69
Head 32
n 88
m 89
b 88

我想解析此文件并将其结构化到下一个平面.我想获取下一个数据:

And I want parse and structure this file to next plane. I want to get next data:

Head 1, f 88
Head 4, t 88
Head 33, v 88
Head 32, n 88
Head 32, b 88

请告诉我如何在红宝石上制作这样的代码?

Please tell me how how can I make such code on a ruby?

我想首先我将所有行都放在数组中:

I think first I have its put all the lines in the array:

lines = Array.new
File.open('C:/file/file.txt', 'r').each { |line| lines << line }

但是接下来我该怎么办?

but what should I do next?

谢谢!

推荐答案

如果@mudasobwa问题的答案是您想获取具有88个价值的所有东西吗?"这是解决方案

If the answer to @mudasobwa question "Do you want to grab everything having 88 value?" this is the solution

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 /\w{1} 88/
    res << "#{current_head}, #{line}"
  end
end

puts res

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆