Ruby 如何匹配Blogspot中属于特定类别的项目
在我的代码中,我有一个部分提取并列出了不同类别的帖子,但我的问题是如何准确地获取属于该类别的帖子并只列出它们。这是我的代码示例:Ruby 如何匹配Blogspot中属于特定类别的项目,ruby,Ruby,在我的代码中,我有一个部分提取并列出了不同类别的帖子,但我的问题是如何准确地获取属于该类别的帖子并只列出它们。这是我的代码示例: category = Array.new docs.elements.each("*/entry/category") { |element| category << element.attributes['term']} title = Array.new docs.elements.each("*/entry/title") do |element
category = Array.new
docs.elements.each("*/entry/category") { |element|
category << element.attributes['term']}
title = Array.new
docs.elements.each("*/entry/title") do |element|
title << element.text
end
category.each_with_index {|category, index|
puts " For Catergory : #{category}
The title is : #{title[index]} "
puts '---------------------------------------------------'
category=Array.new
元素。每个(“*/entry/category”){元素|
category很难弄清楚你的代码是做什么的,因为它实际上不起作用。显然,它解析了一些数据,但你没有告诉我们它是如何解析这些数据的,这些数据是什么,你也没有提供任何示例数据。此外,它似乎取决于一些库,但你没有告诉我们这些库是什么局部变量docs
似乎是您代码中最重要的部分,但它没有定义。您只向我们显示了您不想要的输出,而不是您想要的输出
无论如何,据我所知,这似乎是你想要的:
require 'open-uri'
require 'nokogiri'
doc = Nokogiri.XML(open('http://googleblog.blogspot.com/atom.xml'))
puts doc.css('entry').reduce(Hash.new {|hsh, key| hsh[key] = [] }) {|cats, entry|
cats.tap {|cats|
entry.css('category').each {|cat|
cats[cat['term']] << entry.css('title').text
}
}
}.reduce('') {|s, (cat, titles)|
s.tap {|s|
s << " For Category : #{cat}\n"
s << titles.reduce('') {|s, title|
s.tap {|s|
s << "The title is : #{title}\n"
}
}
s << "---------------------------------------------------\n"
}
}
需要“打开uri”
需要“nokogiri”
doc=Nokogiri.XML(打开)http://googleblog.blogspot.com/atom.xml'))
放置doc.css('entry').reduce(Hash.new{{hsh,key{hsh[key]=[]){cats,entry|
猫,轻拍{猫|
entry.css('category')。每个{| cat|
猫[猫[术语]]有时,挫折会让人做不到的事情。我很抱歉我在问题中犯了这样的错误,但感谢上帝,你能够理解我所说的。文档是我从一个net/http调用中得到的响应的主体。我想匹配REXML文档“doc”的根元素,它包括Post_Id、Category,文章内容,作者,发布日期。所以上面的代码是从我的主代码中挑选出来的。