Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 使用Nokogiri/Rspec一次解析多个文件_Ruby_Rspec_Nokogiri - Fatal编程技术网

Ruby 使用Nokogiri/Rspec一次解析多个文件

Ruby 使用Nokogiri/Rspec一次解析多个文件,ruby,rspec,nokogiri,Ruby,Rspec,Nokogiri,我有一个主解析方法,它由解析html文件的其他方法组成: class Parser def self.parse(html) @data = Nokogiri.HTML(open(html)) merged_hashes = {} array_of_hashes = [ parse_title, parse_description, parse_related ] array_of_hashes.inject(me

我有一个主解析方法,它由解析html文件的其他方法组成:

class Parser
  def self.parse(html)
    @data = Nokogiri.HTML(open(html))
    merged_hashes = {}

    array_of_hashes = [
      parse_title,
      parse_description,
      parse_related
    ]
    array_of_hashes.inject(merged_hashes,:update)

    return merged_hashes
  end

  def self.parse_title
    title_hash = {}

    title = @data.at_css('.featureProductInfo a')
    return title_hash if title.nil?
    title_hash[:title] = @data.at_css('.featureProductInfo a').text

    title_hash
  end
  .
  .
  .
所以我在Rspec中这样做:

require File.dirname(__FILE__) + '/parser.rb'

def html_starcraft
  File.open("amazon_starcraft.html")
end

describe ".parse_title (StarCraft)" do
  let(:title_hash) { Parser.parse html_starcraft } 

  it "scraps the featured product title" do
    expect(title_hash[:title]).to eq("StarCraft II: Wings of Liberty (Bradygames Signature Guides)")
  end
end

正如您所看到的,我一次只解析一个文件。我怎样才能同时解析多个呢?比如说,解析文件夹中的所有文件?

正如@theTinMan所指出的,Nokogiri一次只处理一个文件。如果要解析文件夹中的所有文件,则必须读取文件夹(同样,正如@theTinMan所指出的)和/或每个文件夹

当然,你首先需要理解或理解

使用流程的示例 好的,让我们使用一个进程,因为ruby没有真正的线程:

files = Dir.glob("files/**")

files.each do |file|
  # Here the program become two: 
  # One executes the block, other continues the loop
  fork do 
    puts File.open(file).read
  end
end

# We need to wait for all processes to get to this point
# Before continue, because if the main program dies before
# its children, they are killed immediately. 
Process.waitall
puts "All done. closing."
以及输出:

$ ls files/
a.txt  b.txt  c.txt  d.txt
$ ruby script.rb 
Content of a.txt
Content of b.txt
Content of d.txt
Content of c.txt
All done. closing.

请注意,由于它是并发的,因此每次执行程序时读取文件的顺序都会发生变化。

您一次只能解析一个文件,因为Nokogiri一次只能处理一个文件,这将您的代码限制在这一点上。如果您想处理目录中的所有文件,您需要对它们进行循环并按顺序解析每一个文件,并存储适合您的代码的解析信息。请参阅
Dir[]
Dir.glob
Find.Find
,了解如何循环目录或目录层次结构中的文件。添加一个使用流程的示例,您可能需要看一看。您可以编写好的小代码来完成答案,您可以在此处执行此操作。请你努力一下好吗。虽然我在这门学科上很弱,否则我会补充说:)@Babai添加了一个您可能想要检查的示例非常感谢!!我很高兴……)