[英]Ruby - parsing a text file
我是 Ruby 的新手,一直在嘗試一些非常基本的文本解析。 然而,我現在正在嘗試解析更多的復雜文件,然后將其推送到 csv 文件(我之前沒有做過)並且我陷入了困境。
該文件如下所示,
Title
some text
some different text
Publisher: name
Published Date: date
Number1: number
Number2: number
Number3: number
Category: category
----------------------
Title
some text
some different text
Publisher: name
Published Date: date
Number1: number
Number2: number
Number3: number
Category: category
----------------------
等等
每行代表 csv 中的一個新“列”。
有人可以伸出援手嗎?
太感謝了!
以下是您的一般想法
File.open( thefile ).each do |line|
print line without the new line if line does not contain /--+/
if line contains /--+/
print line with a new line
end
end
這是一個完整的解決方案。 請注意,它對文件結構非常敏感!
out_file = File.open('your_csv_file.csv', 'w')
out_file.puts "Title,Publisher,Publishedate,Number1,Number2,Number3,Category"
the_line = []
in_title = false
IO.foreach('your_file_name') do |line|
if line =~ /^-+$/
out_file.puts the_line.join(',')
the_line = []
elsif line =~ /^Title$/
in_title = true
elsif line =~ /^(?:Publishe(?:r|d Date)|Number\d|Category):\s+(.*?)$/
the_line += [$1]
in_title = false
elsif in_title
the_line[0] = (the_line.empty? ? line.chomp : "\"#{the_line[0]} #{line.chomp}\"")
else
puts "Error: don't know what to do with line #{line}"
end
end
out_file.close
Ruby 2.6.5
some_file = "/path/to/file.extension"
if File.exist?(some_file)
File.open(some_file).each do |line|
if line.include?('some_string')
puts "line: #{line}"
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.