Source code for Business
""" Class example for storing complex object for storing both information
and supporting methods that are specific to this object. It illustrates
the use of another class (Point2d) and its methods.
A business is populated with information from Yelp for businessses near
RPI. An example use is given below.
"""
import Point2d
import simplejson
import textwrap
class Business(object):
[docs] def __init__ ( self, name, address, latitude, longitude, reviews):
"""Create a new business object.
* self.name: name string
* self.latitude, self.longitude: floats for business location
* self.reviews: a list of lists of type [stars:string, text:string]
(number of stars the review gave and text of the review.
"""
self.name = name
self.address = address
self.location = Point2d.Point2d(latitude, longitude)
self.reviews = reviews
self.reviews.sort(reverse=True)
[docs] def __str__(self):
""" Print basic business info. """
return "%s (%s) " %(self.name,\
self.address.replace("\n", ", "))
[docs] def distance_to_rpi(self):
""" Return the Haversine distance to RPI Union. """
rpi = Point2d.Point2d(42.73, -73.68)
return self.location.haversine(rpi)
[docs] def print_best_reviews(self):
""" Prints a string containing the top 2 and bottom 2 reviews
for this business, based on the number of stars.
"""
outline = "*"*60 + "\n"
for [stars,text] in (self.reviews[:2] + self.reviews[-2:]):
for line in textwrap.wrap(text[:200]+"..." + "(%s stars)" %stars, 60):
outline += line + "\n"
outline += "*"*60 + "\n"
return outline
if __name__ == "__main__":
reviews = {}
##key: business id, value: list of reviews: [stars, text]
for line in open("reviews.json"):
m = simplejson.loads(line)
review = [ m['stars'], m['text'] ]
bid = m['business_id']
if bid not in reviews.keys():
reviews[bid] = []
reviews[bid].append( review )
i = 0
blist = {}
for line in open("businesses.json"):
m = simplejson.loads(line)
bid = m['business_id']
b = Business( m['name'], \
m['full_address'], \
m['latitude'],\
m['longitude'],
reviews[bid])
blist[bid] = b
i += 1
if i > 10:
break
bid_list = blist.keys()
while (True):
for i in range(len(bid_list)):
bid = bid_list[i]
print "%d. %s" %(i+1, blist[bid])
choice = raw_input("Enter an index (-1 to exit) ==> ")
if choice == '-1':
break
if choice.isdigit() and 1<= int(choice) <= len(bid_list):
choice = int(choice)
bid = bid_list[choice-1]
business = blist[bid]
business.print_best_reviews()
raw_input("...")
print