Подтвердить что ты не робот

Ruby - разбор текстового файла

Я новичок в 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.

Может кто-нибудь может протянуть руку?

Большое вам спасибо!

4b9b3361

Ответ 1

Вот общая идея для вас начать с

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

Ответ 2

Здесь одно полное решение. Обратите внимание, что он очень чувствителен к файловой структуре!

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