#!/usr/bin/env python # # rate_books.py - v0.1 # # Copyright (c) 2008 - Rich Burridge - Sun Microsystems Inc. # All Rights Reserved. # # Usage: # # $ python ./rate_books.py < library_export.xml > book_ratings.txt # # Script to take an export on my book collection from tellico (in XML # format) on stdin, and for each entry, get the Amazon star rating for # that book and writes the book title, ISBN, average rating and total # number of ratings to stdout. # # Uses PyAWS, a Python wrapper for the latest Amazon Web Service by Kun Xi. # [http://pyaws.sourceforge.net/] # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. import ecs import operator import sys # ------ START OF CONFIGURABLE SECTION ---- # Amazon Access License Key. # amazonAccessKey = "XXXXXXXXXXXXXXXXXXXX" # ------ END OF CONFIGURABLE SECTION ------ def getRatings(ISBNs): ratings = [] for isbn in ISBNs: sys.stderr.write("Checking: %s\n" % isbn) try: results = ecs.ItemLookup(isbn, ResponseGroup='Large') except: sys.stderr.write("**Invalid value: %s. Ignoring\n" % isbn) else: title = results[0].Title if "CustomerReviews" in dir(results[0]): averageRating = float(results[0].CustomerReviews.AverageRating) totalReviews = int(results[0].CustomerReviews.TotalReviews) else: averageRating = 0.0 totalReviews = 0 rating = { "title":title, "isbn":isbn, \ "average":averageRating, "total":totalReviews } ratings.append(rating) return ratings def sortRatings(ratings): sortedRatings = sorted(ratings, key=operator.itemgetter('average', 'total')) sortedRatings.reverse() return sortedRatings def printRatings(ratings): for rating in ratings: title = rating["title"] isbn = rating["isbn"] averageRating = rating["average"] if averageRating == "0": averageRating = "unrated" totalReviews = rating["total"] try: line = "'%s'\t(ISBN: %s)\t%s reviews\t(%s stars)" % \ (title, isbn, totalReviews, averageRating) print line except: sys.stderr.write("**Can't print results for: %s.\n" % isbn) def getISBNs(lines): allISBNs = [] for i in range(0, len(lines)): line = lines[i].strip() if line.startswith(""): isbn = line.replace("", "") isbn = isbn.replace("", "") isbn = isbn.replace("-", "") allISBNs.append(isbn) return allISBNs if __name__ == "__main__": ecs.setLicenseKey(amazonAccessKey) ISBNs = getISBNs(sys.stdin.readlines()) printRatings(sortRatings(getRatings(ISBNs))) # ChangeLog # 18th May 2008 - 0.1 - richb - Initial version.