import os
import urllib2
import re
from xml.dom.minidom import parseString, Node

'''
"http://isbndb.com/api/books.xml?access_key=12345678&index1=isbn&value1=0596002068"


'''
def parseXML(xml):
    bookData = {}
    xmltree = parseString(xml)
    print xml
    for node1 in xmltree.getElementsByTagName('BookData'):
        for node2 in node1.childNodes: 
            if node2.nodeType == Node.ELEMENT_NODE: 
                if node2.hasChildNodes():
                    print node2.nodeName,node2.childNodes[0].data
                    bookData[node2.nodeName]=node2.childNodes[0].data
    return bookData

def newName(isbn,bookData):
    sep = "."
    newName = bookData["PublisherText"]+sep+bookData["Title"]+sep+fixAuthorsText(bookData["AuthorsText"])+sep+isbn            
    return newName

def findISBN(filename):
    isbn13 = re.findall("[0-9]{13}", filename)
    if isbn13: return isbn13
    isbn = re.findall("[0-9]{9}[0-9X]", filename)
    return isbn

def fixAuthorsText(text):
    return text[:-2]


key = "QIQXU438"
path = "/Volumes/passport/ebooks/isbn/"
baseUrl = "http://isbndb.com/api/books.xml?access_key=" + key

os.chdir(path)

for root, dirs, files in os.walk(path):
        for file in files:
            
            ext = os.path.splitext(file)[1]
            
            isbn = findISBN(file[:-4])
            if not isbn : continue
            
            isbn = isbn[0]
            
            url = baseUrl +  "&index1=isbn&value1=" + isbn
    
            xml = urllib2.urlopen(url).read()
            
            bookData = parseXML(xml)
            if bookData:
                os.rename(file, newName(isbn,bookData) + ext)
Annunci