lolamontes69

Rewrites of geoGrab() and massPlaceFind() from MLIA Ch10.

Dec 1st, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. """ geoGrab() and massPlaceFind() from Machine Learning in Action Chapter 10.
  2.  
  3.    Seems as though the book versions were not working I wrote versions
  4.    using YQL that parses the returned XML for the latitudes and longitudes.
  5.    After all I wouldn't want to miss out on Drew's Pubcrawl :)
  6.                          --lolamontes69
  7. """
  8.  
  9. import urllib2 as urllib2
  10. import xml.etree.ElementTree as ET
  11. from time import sleep
  12.  
  13. def geoGrab(address):
  14.     apiStem = 'http://query.yahooapis.com/v1/public/yql?q='
  15.     apiStem1 = 'select%20*%20from%20geo.placefinder%20where%20text="'
  16.     apiTail = '"'
  17.     address = address.replace(' ','%20')
  18.     url = apiStem+apiStem1+address+apiTail
  19.     print url
  20.     geoxml = urllib2.urlopen(url)
  21.     tree = ET.parse(geoxml)
  22.     root = tree.getroot()
  23.     latitude = (root[0][0].find('latitude')).text
  24.     longitude = (root[0][0].find('longitude')).text
  25.     print float(latitude),float(longitude)
  26.     return float(latitude),float(longitude)
  27.  
  28. def massPlaceFind(fileName):
  29.     fw = open('places.txt', 'w')
  30.     for line in open(fileName).readlines():
  31.         line = line.strip()
  32.         line1 = line.split('\t')
  33.         lineArr = ' '.join(line1[1:])
  34.         try: latt,lng = geoGrab(lineArr)
  35.         except: pass
  36.         try:
  37.             print "%s\t%f\t%f" % (lineArr, latt, lng)
  38.             fw.write('%s\t%f\t%f\n' % (line, latt, lng))
  39.         except: print "error fetching"
  40.         sleep(1)
  41.     fw.close()
  42.  
  43. if __name__ == "__main__":
  44.     massPlaceFind("portlandClubs.txt")
Advertisement
Add Comment
Please, Sign In to add comment