конкатенация в файлах - PullRequest
       3

конкатенация в файлах

0 голосов
/ 29 ноября 2011
files = ["message_21.txt", "message_10.txt", "message_27.txt", "message_22.txt", "message_23.txt", "message_15.txt", "message_4.txt", "message_16.txt", "message_24.txt", "message_13.txt", "message_1.txt", "message_3.txt", "message_17.txt", "message_12.txt", "message_2.txt", "message_19.txt", "message_18.txt", "message_14.txt", "message_25.txt", "message_9.txt", "message_8.txt", "message_5.txt", "message_26.txt", "message_11.txt", "message_7.txt", "message_20.txt", "message_6.txt", "message_28.txt"]

def check_StubHub(file)
foo = File.open(PATH + "/" + file, 'r').read
foo.index(/StubHub/) ? true : false
end

def check_Ticketmaster(file)
foo = File.open(PATH + "/" + file, 'r').read
foo.index(/Ticketmaster/) ? true : false
end

@count = 0
files.each do |f|
@count = @count + 1
puts "Processing: " + f 

if check_StubHub(f)
    file = File.new(PATH + "/" + f, "r")

    while (line = file.gets)
        line = line.strip
            @event = line if line.match(/^Event/)
            @venue = line if line.match(/^Venue/)
            @date =  line if line.match(/^Date/)
        found = true if line.match(/^Date/)
        break if found
    end
 p @event,@venue,@date
    file.close

end

if check_Ticketmaster(f)
    @found = false
    file = File.new(PATH + "/" + f, "r")
    while (line = file.gets)
         @found=true if line =~ /You purchased/
         next unless @found
         puts line
         break if line =~ /Order for/
    end
    file.close

end
 File.open("/home/spritle/Desktop/vino-tryouts/fomo_r/specific_terms/terms.txt", 'w') do |f|
   f.puts @event,@venue,@date
  end
 end

В терминале я получаю

Processing: message_21.txt
Processing: message_10.txt
Processing: message_27.txt
"Event:    NBA Eastern Conference Semifinals Tickets: Orlando Magic at Boston Celtics - Home Game 1"
"Venue:    TD Banknorth Garden , Boston, MA"
"Date:    05-04-2009 08:00 PM EST"
Processing: message_22.txt
"Event:    Los Angeles Clippers at Boston Celtics Tickets"
"Venue:    TD Garden , Boston, MA"
"Date:    01-25-2010 07:30 PM EST"
Processing: message_23.txt
"Event:    Los Angeles Clippers at Boston Celtics Tickets"
"Venue:    TD Garden , Boston, MA"
"Date:    01-25-2010 07:30 PM EST"
Processing: message_15.txt
Processing: message_4.txt
You purchased 2 tickets to: 
_____________________________________________________________________________________________ 
The Temper Trap
Webster Hall, New York, NY
Fri, Apr 2, 2010 07:00 PM 

Order for: Vikas Sekhri
Processing: message_16.txt
Processing: message_24.txt
"Event:    NBA Eastern Conference Semifinals Tickets: Orlando Magic at Boston Celtics - Home Game 3 (Game #5)"
"Venue:    TD Banknorth Garden , Boston, MA"
"Date:    05-12-2009 08:00 PM EST"
Processing: message_13.txt
You purchased 1 ticket to: 
_____________________________________________________________________________________________ 
XPN Welcomes TV On The Radio, Celebration, and Saturn Never Sleeps
The Electric Factory, Philadelphia, PA
Fri, Apr 8, 2011 08:30 PM  

Order for: vikas sekhri
Processing: message_1.txt
Processing: message_3.txt
Processing: message_17.txt
Processing: message_12.txt
You purchased 4 tickets to: 
_____________________________________________________________________________________________ 
O.A.R.
Bank of America Pavilion, Boston, MA
Thu, Jul 29, 2010 07:00 PM 

Order for: Vikas Sekhri
Processing: message_2.txt
Processing: message_19.txt
You purchased 1 ticket to: 
_____________________________________________________________________________________________ 
XPN Welcomes TV On The Radio, Celebration, and Saturn Never Sleeps
The Electric Factory, Philadelphia, PA
Fri, Apr 8, 2011 08:30 PM  

Order for: vikas sekhri
Processing: message_18.txt
Processing: message_14.txt
Processing: message_25.txt
"Event:    NBA Eastern Conference Semifinals Tickets: Orlando Magic at Boston Celtics - Home Game 3 (Game #5)"
"Venue:    TD Banknorth Garden , Boston, MA"
"Date:    05-12-2009 08:00 PM EST"
Processing: message_9.txt
You purchased 2 tickets to: 
_____________________________________________________________________________________________ 
Broken Bells with The Morning Benders
Royale Boston, Boston, MA
Fri, Jun 4, 2010 05:30 PM 

Order for: Vikas Sekhri
Processing: message_8.txt
Processing: message_5.txt
You purchased 2 tickets to: 
____________________________________________________________________________
_________________ 
The Temper Trap
Webster Hall, New York, NY
Fri, Apr 2, 2010 07:00 PM 

Order for: Vikas Sekhri
Processing: message_26.txt
"Event:    NBA Eastern Conference Semifinals Tickets: Orlando Magic at Boston Celtics - Home Game 1"
"Venue:    TD Banknorth Garden , Boston, MA"
"Date:    05-04-2009 08:00 PM EST"
Processing: message_11.txt
Processing: message_7.txt
You purchased 2 tickets to: 
____________________________________________________________________________
_________________ 
The Temper Trap
Webster Hall, New York, NY
Fri, Apr 2, 2010 07:00 PM 

Order for: Vikas Sekhri
Processing: message_20.txt
"Event:    NBA Eastern Conference Semifinals Tickets: Orlando Magic at Boston Celtics - Home Game 1"
"Venue:    TD Banknorth Garden , Boston, MA"
"Date:    05-04-2009 08:00 PM EST"
Processing: message_6.txt
You purchased 2 tickets to: 
____________________________________________________________________________
_________________ 
The Temper Trap
Webster Hall, New York, NY
Fri, Apr 2, 2010 07:00 PM 

Order for: Vikas Sekhri
Processing: message_28.txt
"Event:    NBA Eastern Conference Semifinals Tickets: Orlando Magic at Boston Celtics - Home Game 1"
"Venue:    TD Banknorth Garden , Boston, MA"
"Date: Tue, Apr 28, 2009 at 3:01 PM"

Но в написанном файле я получаю только последние путы.Файл удаляет предыдущую информацию и показывает только последнюю.Я хочу показать всю информацию, возвращенную в файле @event, @venue, @date.Я не знаю, как сделать, присоединиться к предыдущему сообщению с текущим сообщением.Кто-нибудь может мне помочь?

Ответы [ 3 ]

2 голосов
/ 29 ноября 2011

Каждый @event, @venue и @data содержит один фрагмент данных. Кажется, вы перезаписываете значения перед сохранением их в файл. Пытаться положить

puts "Writing to file"

Прямо перед строкой f.puts.

Вы, вероятно, увидите, что это происходит после того, как произошла другая обработка. Вы хотите печатать каждый раз, когда вы обновляете 3 значения.

Я бы открыл выходной файл в начале вашего скрипта и либо передал его, либо установил в качестве переменной экземпляра (@file). Затем каждый раз, когда вы делаете путы, также делайте @ file.puts.

Вы также можете сделать @event, ... массивами и вместо того, чтобы назначать им, сделать что-то вроде этого:

#initialization
@output = []
#...
@output.push(line) if line.match(/^Event/)
@output.push(line) if line.match(/^Date/)

Затем распечатайте @events в конце.

0 голосов
/ 29 ноября 2011

У вас неправильный режим открытия для вашего файла

 File.open("YOUR_PATH_TO_FILE", 'w') do |f|
   f.puts @event,@venue,@date
 end

если вы проверите документацию вы увидите

"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.

вам нужно a+ или одиниз

Mode |  Meaning
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
0 голосов
/ 29 ноября 2011
files = ["message_21.txt", "message_10.txt", "message_27.txt", "message_22.txt", "message_23.txt", "message_15.txt", "message_4.txt", "message_16.txt", "message_24.txt", "message_13.txt", "message_1.txt", "message_3.txt", "message_17.txt", "message_12.txt", "message_2.txt", "message_19.txt", "message_18.txt", "message_14.txt", "message_25.txt", "message_9.txt", "message_8.txt", "message_5.txt", "message_26.txt", "message_11.txt", "message_7.txt", "message_20.txt", "message_6.txt", "message_28.txt"]

def check_StubHub(file)
  foo = File.open(PATH + "/" + file, 'r').read
  foo.index(/StubHub/) ? true : false
end

def check_Ticketmaster(file)
  foo = File.open(PATH + "/" + file, 'r').read
  foo.index(/Ticketmaster/) ? true : false
end

@count = 0
files.each do |f|
  @count = @count + 1
  puts "Processing: " + f 

  if check_StubHub(f)
      file = File.new(PATH + "/" + f, "r")

      while (line = file.gets)
          line = line.strip
            @event = line if line.match(/^Event/)
            @venue = line if line.match(/^Venue/)
            @date =  line if line.match(/^Date/)
        found = true if line.match(/^Date/)
        break if found
      end
      puts @event,@venue,@date
      f.puts @event,@venue,@date
      file.close

  end

  if check_Ticketmaster(f)
      @found = false
      file = File.new(PATH + "/" + f, "r")
      while (line = file.gets)
         @found=true if line =~ /You purchased/
         next unless @found
         f.puts line
         puts line
         break if line =~ /Order for/
      end
      file.close

  end
  File.open("/home/spritle/Desktop/vino-tryouts/fomo_r/specific_terms/terms.txt", 'w') do |f|
   puts @event,@venue,@date
   f.puts @event,@venue,@date
  end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...