Comparison of ruby and python line by line (2/3)
In the first part of this series, you see how ruby and python retrieve data from given URL and then parse the results using regular expression. In part two, the code is extended to query prices from Amazon through Amazon Web Services.
- Specify executable
Ruby#!/usr/bin/ruby
Python#!/usr/bin/python
- Import modules
Rubyrequire ’net/http’ require ’rexml/document’
Pythonimport sys import re import urllib from xml.dom.ext.reader import Sax2 from xml.dom.ext import Print from xml import xpath
- Validate argument
Rubyif ARGV.length == 0 puts "#{$0}: You must enter at least one argument" exit endPythonif len(sys.argv) == 1: print "%s: You must enter at least one argument." % sys.argv[0] sys.exit() - Initialize output and regular expressions
Rubyoutput = "" not_in_collection_re = /class="yourEntryWouldBeHereData"/ix on_shelf_re = /CHECK SHELF/ix checked_out_re = /DUE /ix
Pythonoutput = ’’ not_in_collection_re = re.compile(r’class="yourEntryWouldBeHereData"’,re.I) on_shelf_re = re.compile(r’CHECK SHELF’,re.I) checked_out_re = re.compile(r’DUE ’,re.I)
- Start loop
RubyARGV.each do |isbn|
Pythonfor isbn in sys.argv[1:]:
- Validate input
Rubyif not isbn.match(/[0-9xX]{10}/) output << "ISBN #{isbn} is invalid.\n" next end output << "ISBN: #{isbn}\n"Pythonif not re.match(r’[0-9xX]{10}’,isbn): output += ’ISBN %s is invalid.\n’ % isbn continue output += ’ISBN: %s\n’ % isbn - Query AWS
Rubyamazon_params = {’Service’ => ’AWSECommerceService’, ’Operation’ => ’ItemLookup’, ’AWSAccessKeyId’ => ’XXXXXXXXXXXXXXXXXXX’, ’ItemId’ => isbn, ’ResponseGroup’ => ’Medium,OfferFull’, ’MerchantId’ => ’All’}.map{|key,value|"#{key}=#{value}"}.join("&") amazon_response = Net::HTTP.get_response(’webservices.amazon.com’, ’/onca/xml?’ << amazon_params)Pythonamazon_params = { ’Service’: ’AWSECommerceService’, ’Operation’: ’ItemLookup’, ’AWSAccessKeyId’: ’XXXXXXXXXXXXXXXXXXX’, ’ItemId’: isbn, ’ResponseGroup’: ’Medium,OfferFull’, ’MerchantId’: ’All’, } amazon_response = urllib.urlopen(’http://webservices.amazon.com/onca/xml’,urllib.urlencode(amazon_params)) - Parse XML
Rubyxml = REXML::Document.new(amazon_response.body)
Pythonxml = Sax2.FromXmlStream(amazon_response).documentElement
- Extract information from the XML
Rubynew_price = xml.root.elements["Items/Item/OfferSummary/LowestNewPrice/FormattedPrice"] if new_price.nil? output << "\tNew: None available\n" else output << "\tNew: #{new_price.text}\n" end used_price = xml.root.elements["Items/Item/OfferSummary/LowestUsedPrice/FormattedPrice"] if used_price.nil? output << "\tUsed: None available\n" else output << "\tUsed: #{used_price.text}\n" end collectible_price = xml.root.elements["Items/Item/OfferSummary/LowestCollectiblePrice/FormattedPrice"] if collectible_price.nil? output << "\tCollectible: None available\n" else output << "\tCollectible: #{collectible_price.text}\n" endPythontry: new_price = xpath.Evaluate(’Items/Item/OfferSummary/LowestNewPrice/FormattedPrice’,xml)[0] output += ’\tNew: %s\n’ % new_price.childNodes[0].nodeValue except: output += ’\tNew: None\n’ try: used_price = xpath.Evaluate(’Items/Item/OfferSummary/LowestUsedPrice/FormattedPrice’,xml)[0] output += ’\tUsed: %s\n’ % used_price.childNodes[0].nodeValue except: output += ’\tUsed: None\n’ try: collectible_price = xpath.Evaluate(’Items/Item/OfferSummary/LowestCollectiblePrice/FormattedPrice’,xml)[0] output += ’\tCollectible: %s\n’ % collectible_price.childNodes[0].nodeValue except: output += ’\tCollectible: None\n’ - Query Skokie
Rubyresponse = Net::HTTP.get_response(’catalog.skokielibrary.info’, "/search~S4/i?SEARCH=#{isbn}")Pythonresponse = urllib.urlopen(’http://catalog.skokielibrary.info/search~S4/i’,’SEARCH=%s’ % isbn) body = response.read() - Parse the result
Rubyif not_in_collection_re.match(response.body) output << "ISBN #{isbn} is not in the Skokie collection.\n" elsif on_shelf_re.match(response.body) output << "ISBN #{isbn} is on the shelf.\n" elsif checked_out_re.match(response.body) output << "ISBN #{isbn} is currently checked out.\n" else output << "ISBN #{isbn} response: Unparseable!.\n" endPythonif not_in_collection_re.search(body): output += ’ISBN %s is not in the Skokie collection.\n’ % isbn elif on_shelf_re.search(body): output += ’ISBN %s is on the shelf.\n’ % isbn elif checked_out_re.search(body): output += ’ISBN %s is currently checked out.\n’ % isbn else: output += ’ISBN %s response: Unparseable!\n’ % isbn - End loop
Rubyend
Python - Print output
Rubyputs output
Pythonprint output
Not too bad! Python can do what Ruby do but slightly longer due to too simple syntax, especially, XML APIs. Ruby comes with rexml while Python has pyxml as an external package. So choosing Ruby and Python cannot be done based on just syntax or features. It is up to you. Do you like short and compact code? Do you like clean and clear code?
Don't forget to read part 1, 2, 3.
Technorati Tags: English, IT, Programming, Python, Tips and Tricks, Ruby, XML, Rexml, Pyxml
- sugree's blog
- 840 reads

Video Converter for Mac is
Video Converter for Mac is the most powerful Video Converter for Mac OS software which allows you to convert videos between popular video formats and audio formats. The easy-to-use Video Converter for Mac lets you to enjoy your videos on iPod, PSP, Mobile Phone, Zune, iPhone, Apple TV and MP4/MP3 player. This Video Converter for Mac allows you to set the destination, the name of output files.iPod Converter for Mac is the best Video to iPod Converter for Mac OS X software for you. With the iPod Converter for Mac you can easily convert popular video formats including FLV, MPEG1, MPEG2, DivX, Xvid, WMV, 3GP, 3G2, MOV, AVI, MPEG TS/TP (for HD Video), etc to iPod compatible MPEG-4 videos. And also it is not only and iPod Converter for Mac, but it can convert all popular videos to iPhone, Apple TV, PSP, PS3, Youtube (web), Creative Zen, iRiver PMP, Archos, MP4, various mobile phones and many other digital video and audio players.MP4 Converter for Mac is an excellent Mac MP4 converter which can not only convert MP4 to MP3, WMA, AAC, WAV, etc but also convert avi, flv, wmv, mpeg, divx etc to MP4 on Mac os x to enjoy your favourite video with MP4 Converter for Mac os. Compared with other mp4 converter Mac software, the MP4 Converter for Mac provides powerful edit functions, such as setting the output settings, cropping and trimming files, merging several files into one, etc. With this MP4 Converter for Mac, you can easily convert mp4 videos to varoius format for Mac.
FLV Converter Mac is a
FLV Converter Mac is a powerful FLV Converter for Mac software which can convert FLV video files to all popular video formats and convert FLV to popular audio formats for Mac OS X users. FLV Converter Mac OS X softwrare supports all video popular formats indcluding FLV, MPG, MPEG1, MPEG2, MP4, 3GP, 3G2, MOV, AVI, Mpeg TS/TP (for HD Video), etc. The Mac FLV Converter can also convert FLV to MP3, WAV, OGG, 3GP, AAC and M4A, AC3, APE, etc audio.
How to download YouTube videos for Mac and convert the .FLV files on Mac OS? Here are the easy-to-use and top-user-rating YouTube Video Grabber Mac and Mac FLV converter tools. It is safe to install and no spyware or adware guarenteed.
With the YouTube Video Grabber Mac application, you can easily download youtube for mac and convert YouTube videos on your Mac OS. It can automatically detect the YouTube video files from the YouTube web pages you have opened and download multiple files once a time. YouTube Video Grabber Mac is a totally free download youtube videos for mac, because if you don’t want to convert downloaded videos to your mobile players, you don’t have to pay for it.
Post new comment