解析Zip文件并从文本文件中提取记录

时间:2012-06-28 16:16:51

标签: ruby file

我是Ruby的新手,可以在程序中使用一些帮助。我需要打开一个包含多个文本文件的zip文件,这些文件包含许多行数据(例如)

CDI|3|3|20100515000000|20100515153000|2008|XXXXX4791|0.00|0.00
CDI|3|3|20100515000000|20100515153000|2008|XXXXX5648|0.00|0.00
CHO|3|3|20100515000000|20100515153000|2114|XXXXX3276|0.00|0.00
CHO|3|3|20100515000000|20100515153000|2114|XXXXX4342|0.00|0.00
MITR|3|3|20100515000000|20100515153000|0000|XXXXX7832|0.00|0.00
HR|3|3|20100515000000|20100515153000|1114|XXXXX0238|0.00|0.00

我首先需要提取zip文件,读取zip文件中的文本文件,并将只有(CDICHO)开头的完整行写入两个输出文件,一个用于以CDI开头的数据行和以CHO开头的数据行的数据行(基本上解析文件)。我必须使用Ruby并且可能尝试将程序设置为自动函数以获得相同身份的连续zip文件。我非常感谢任何人给出的建议,方向或帮助。

2 个答案:

答案 0 :(得分:0)

一种方法是使用ZipFile库。

require 'zip/zip'

# To open the zip file and pass each entry to a block
Zip::ZipFile.foreach(path_to_zip) do |text_file|
   # Read from entry, turn String into Array, and pass to block
   text_file.read.split("\n").each do |line|
      if line.start_with?("CDI") || line.start_with?("CHO")
         # Do something
      end
   end
end

答案 1 :(得分:0)

我不确定我是否完全听从你的问题。首先,如果您想使用Ruby解压缩文件,请查看this question。一旦您将文件解压缩为可读格式,您可以尝试沿着这些行打印到两个单独的输出:

cdi_output = File.open("cdiout.txt", "a")  # Open an output file for CDI
cho_output = File.open("choout.txt", "a")  # Open an output file for CHO

File.open("text.txt", "r") do |f|          # Open the input file
  while line = f.gets                      # Read each line in the input
    cdi_output.puts line if /^CDI/ =~ line # Print if line starts with CDI
    cho_output.puts line if /^CHO/ =~ line # Print if line starts with CHO
  end
end

cdi_output.close                           # Close cdi_output file
cho_output.close                           # Close cho_output file
相关问题