how to match items belonging to a particular category in Blogspot
In my code, I have a section that extracts and lists the different categories of posts but my problem is how to get exactly the posts that fall within that category and list them only. This is an example of my code:
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 '---------------------------------------------------'
The output of the above code is as follows and I would want to match like categories with their titles.
For Catergory : A good Begining
The title is : Today
For Catergory : Circular
The title is : Life
For Catergory : Circular
The title is : Let Me try开发者_Go百科
For Catergory : A good Begining
The title is : Check
For Catergory : time shall time
The title is : Testing
For Catergory : time shall time
The title is : I have made it
For Catergory : Circular
The title is : I have made it
For Catergory : Circular
The title is : Me
For Catergory : A good Begining
The title is : A Remarkable move
For Catergory : time shall time
The title is :
For Catergory : A good Begining
The title is : A welcome note
It's pretty much impossible to figure out what your code does, because it doesn't actually work. Apparently, it parses some data, but you don't tell us how it parses that data, what that data is and you don't provide any example data. Also, it seems that it depends on some libraries, but you don't tell us what those libraries are. The local variable docs
which seems to be pretty much the most important thing in your code, is not defined. And instead of showing us what the output is that you want, you only show us what the output is that you don't want.
Anyway, as far as I have been able to figure out, this seems to be what you want:
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"
}
}
It would also have been nice to know that you are actually processing an Atom feed. If I had known that beforehand, I wouldn't have had to write all that parsing logic myself, I could have just used an Atom parsing library.
精彩评论