Esempio n. 1
0
def z_parse(z, rest_json):
    z_restaurants = rest_json.get('restaurants')
    if z_restaurants:
        for bus in z_restaurants:
            rev_list = []
            res = bus.get('restaurant')
            res_id = res.get('R').get('res_id')
            reviews = z.get_restaurant_reviews(res_id).get('user_reviews')
            if reviews:
                for review in reviews:
                    rev = res.RestaurantReview(
                        review.get('review').get('rating'),
                        review.get('review').get('review_text')
                    )
                    rev_list.append(rev)
            else:
                pass

            restaurant = res.Restaurant(
                res.get('id'),
                res.get('name'),
                float(res.get('user_rating').get('aggregate_rating')),
                str(res.get('price_range')),
                rev_list
            )
            restaurants.append(restaurant)
    else:
        pass
Esempio n. 2
0
    def read_csv(self):
        with open('ranking.csv') as f:
            reader = csv.reader(f)
            l = [row for row in reader]

        for i in range(len(l)):
            r = restaurant.Restaurant(l[i][0], l[i][1])
            self.restaurant_list.append(r)
Esempio n. 3
0
    def get_restaurants(self, yelp_database, locu_database):
        """Gets the top restaurants for a given User.
        Args:
            yelp_database (YelpDatabase): a YelpDatabase object
            locu_database (MenuDatabase): a MenuDatabase object
        Returns:
            restaurants (list): a list of Restaurant objects.
        """
        restaurants = []

        # Look for the query in the yelp_database, and if it is, load the response from the database
        if ((self.term, self.location)) in yelp_database.data:
            print 'Found ' + self.term + ' in Yelp database!'
            responses = yelp_database.data[(self.term, self.location)]
        # Otherwise, make a Yelp API query
        else:
            print 'Querying Yelp for ' + self.term + '...'
            responses = yelp_query.get_restaurant_responses(
                self.term, self.location)
            yelp_database.data[(self.term, self.location)] = responses

        print responses[0]

        # Each response in responses represents a restaurant. Create a Restaurant out of it.
        for i, response in enumerate(responses):
            name = restaurant_attribute_parser.get_name(response)
            address = restaurant_attribute_parser.get_address(response)
            locality = restaurant_attribute_parser.get_locality(response)
            categories = restaurant_attribute_parser.get_categories(response)
            image = restaurant_attribute_parser.get_image(response)
            unenc_name = restaurant_attribute_parser.get_name_nonenc(response)
            url = restaurant_attribute_parser.get_url(response)
            display_name = unidecode(unenc_name)

            # Look for the restaurant in the locu_database. If it is, load the menu from it
            if ((unenc_name, locality)) in locu_database.data:
                print 'Found ' + unenc_name + ' in Locu database!'
                menu = locu_database.data[(unenc_name, locality)]
            #Otherwise, make a Locu query for the menu
            else:
                print 'Querying Locu for ' + unenc_name + '...'
                menu = locu_query.get_menu(unenc_name, locality)
                locu_database.data[(unenc_name, locality)] = menu

            # get the average price of mains from the Locu menu
            price = locu_query.get_price_of_mains(menu)

            # create the restaurant object
            rest = restaurant.Restaurant(name, address, locality, categories,
                                         price, image, unenc_name, url,
                                         display_name)
            restaurants.append(rest)
        return restaurants
def parse(rest_json):
    businesses = rest_json.get('businesses')
    if (businesses):
        for bus in businesses:
            rev_list = []
            reviews = get_reviews(API_KEY, bus.get('id')).get('reviews')
            if (reviews):
                for review in reviews:
                    rev = res.RestaurantReview(review.get('rating'),
                                               review.get('text'))
                    rev_list.append(rev)
            else:
                pass
            restaurant = res.Restaurant(bus.get('id'), bus.get('name'),
                                        bus.get('rating'), bus.get('price'),
                                        rev_list)
            restaurants.append(restaurant)
    else:
        pass
Esempio n. 5
0
    def add_restaurant(self, restaurant_name):
        search_results = self.yelp.search(restaurant_name,
                                          self.city_name)['businesses']

        if len(search_results) == 0:
            return None

        # maybe dumb
        business = search_results[0]
        params = {
            restaurant.RESTAURANT_NAME: business['name'],
            restaurant.RESTAURANT_RATING: business['rating'],
            restaurant.RESTAURANT_REVIEW_COUNT: business['review_count'],
            restaurant.RESTAURANT_CUISINE: business['categories'][0]['alias'],
            restaurant.RESTAURANT_LINK: business['url'].split('?')[0],
            restaurant.RESTAURANT_LOCATION: business['location']['city'],
            restaurant.RESTAURANT_PRICE: business['price']
        }
        self.restaurant_list.append(restaurant.Restaurant(params))
Esempio n. 6
0
    def setUpClass(cls):
        # Called once at the beginning
        print('Class set up')
        cls.restaurant = restaurant.Restaurant()

        # Create dishes
        cls.lasagna = dish.Dish("Lasagna", "Entree", 12.00)
        cls.chocolate_cake = dish.Dish("Chocolate Cake", "Desert", 13.00)

        # Add dishes to the restaurant
        cls.restaurant.add_dish(cls.lasagna)
        cls.restaurant.add_dish(cls.chocolate_cake)

        # Create patrons
        cls.miranda = patron.Patron("Miranda", False)
        cls.derek = patron.Patron("Derek", True)

        # Add patrons to the restaurant
        cls.restaurant.add_patron(cls.miranda)
        cls.restaurant.add_patron(cls.derek)
Esempio n. 7
0
#9-10 imported restaurant

import restaurant as rs


restaurant_0 = rs.Restaurant('morleys', 'chicken')

restaurant_1 = rs.Restaurant('golden grill', 'kebab')

restaurant_2 = rs.Restaurant('fat duck', 'fancy schmancy')

restaurant_0.describe_restaurant()
restaurant_2.describe_restaurant()


restaurant_1.set_number_served(19)

print(restaurant_1.number_served)

restaurant_1.increment_number_served(4)

print(restaurant_1.name.title() + " has served " + 
	str(restaurant_1.number_served) + " peeps today")
Esempio n. 8
0
# -*- coding: utf-8 -*-
import restaurant
import datetime

my_res1 = restaurant.Restaurant('重庆小面', '面馆', 10)
my_res1.get_resInfo()

# 给出固定的时间 9点和23点,测试是否营业
my_res1.get_resWorkingTime(9)
my_res1.get_resWorkingTime(23)
print()

#获取当前时间
now_time = datetime.datetime.now()

print(f"当前时间为{now_time}")
my_res1.get_resWorkingTime(now_time.hour)

print()
my_res1.get_eatingPeople()
my_res1.change_eatingPeople(12)
my_res1.change_eatingPeople(10)

print()
my_res = restaurant.XMRestaurant('小明', '火锅', 10, '四川', 10)
my_res.get_resInfo()
# 正数表示有人入职
my_res.update_employeeNum(1)
# 负数表示离职
my_res.update_employeeNum(-1)
Esempio n. 9
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# 9-10 导入Restaurant类型
import restaurant
restaurant = restaurant.Restaurant('Mcdonald', 'junk food')
restaurant.describe_restaurant()

# 9-11 导入Admin类
#import user
#admin = user.Admin('Augustine', 'Geordie', ['a', 'b', 'c'])
#admin.show_privileges()

# 9-12 多个模块
from user import User
from admin import Admin, Privileges

admin = Admin('Augustine', 'Geordie', ['a', 'b', 'c'])
admin.show_privileges()
Esempio n. 10
0
#         for flavor in self.flavors:
#             print("\t" + flavor)
#
#     def add_flavor(self, flavors):
#         for flavor in flavors:
#             self.flavors.append(flavor)
#
#
# ice_cream_stand = IceCreamStand("tea", "Taiwan")
# flavors = ['mint', 'cho', 'strawberry']
# ice_cream_stand.add_flavor(flavors)
# ice_cream_stand.describe_ice_cream_stand()


# 9-10
restaurant = rt.Restaurant("tea", "Taiwan")
restaurant.describe_restaurant()


# 9-11
dict = OrderedDict()
dict['int'] = 'Integer'
dict['float'] = 'Floating point'
dict['none'] = 'None'
dict['dictionary'] = 'Dictionary type'
dict['list'] = 'List type'

for key, value in dict.items():
    print("Key: " + key + "\tvalue: "+value)

Esempio n. 11
0
import restaurant

first_restuarant = restaurant.Restaurant('McDonald', 'abc')
first_restuarant.describe()
first_restuarant.open_restuarant()
print("first count is "+str(first_restuarant.count))

second_restuarant = restaurant.Restaurant('KFC','Hello')
print(second_restuarant.name);
print("second count is "+str(second_restuarant.count))
second_restuarant.add_count(10)
print("second count is "+str(second_restuarant.count))

print("-------------------")

lemon = restaurant.Fruit('lemon')
ice_cream_restua = restaurant.IceCreamStand('HaGenHash','Big','Ice Cream',lemon)
ice_cream_restua.describe()
ice_cream_restua.show_flavor()
ice_cream_restua.fruit.change_type('watermelon')
ice_cream_restua.show_flavor()

    def scrape(self, url):
        rest = restaurant.Restaurant()
        rest.url = url

        # htmlの抽出
        try:
            response = requests.get(url)
            response.encoding = response.apparent_encoding
            bs = BeautifulSoup(response.text, 'html.parser')
        except:
            print("Error occured when extracting html from , from " + url)
            return rest  # htmlが抽出できないとそれ以上解析ができないため、ここで終了する。

        # 店名の取得
        try:
            restaurant_name = self.__extract_text(
                bs.find(class_='display-name').find('span'))
            rest.name = restaurant_name
        except:
            print("Error occured when extracting restaurant name, from " + url)

        # ジャンルの取得(ジャンルは複数あるが、一番最初に出てきたジャンルを抽出することにする)
        try:
            # dtタグの値が 'ジャンル:' であるdlタグを探し、
            # そのdlタグ内で、実際のジャンル名が書かれているタグ(class名が'linktree__parent-target-text')を抽出する。
            target_dl_tags = bs.find(class_='rdheader-info-data').findAll(
                'dl', {'class': 'rdheader-subinfo__item'})
            for dl_tag in target_dl_tags:
                dt_tag = self.__extract_text(
                    dl_tag.find('dt',
                                {'class': 'rdheader-subinfo__item-title'}))
                genre = ""
                if dt_tag == u'ジャンル:':
                    genre = self.__extract_text(
                        dl_tag.find(class_='linktree__parent-target-text'))
                    break
            rest.genre = genre
        except:
            print("Error occured when extracting genre, from " + url)

        # 食べログスコアの取得
        try:
            score = self.__extract_text(
                bs.find(class_='rdheader-rating__score-val-dtl'))
            rest.score = score
        except:
            print("Error occured when extracting score, from " + url)

        # 夜の予算
        try:
            dinner_budget = self.__extract_text(bs.find(class_='gly-b-dinner'))
            rest.dinner_budget = dinner_budget
        except:
            print("Error occured when extracting dinner budget, from " + url)

        # 昼の予算
        try:
            lunch_budget = self.__extract_text(bs.find(class_='gly-b-lunch'))
            rest.lunch_budget = lunch_budget
        except:
            print("Error occured when extracting lunch budget, from " + url)

        # 所在地
        try:
            address = self.__extract_text(
                bs.find(class_='rstinfo-table__address'))
            rest.address = address
        except:
            print("Error occured when extracting address, from " + url)

        return rest
Esempio n. 13
0
def main():

    #attempt to load from file. If fails, just create new restaurant object
    restaurant_attempt = get_restaurant_from_file()
    if (restaurant_attempt == None): restaurant1 = restaurant.Restaurant()
    else: restaurant1 = restaurant_attempt

    while (True):
        print("\nWelcome to restaurant Dingo! How may we help you today?")
        print("1: Check tables")
        print("2: Reserve a table")
        print("3: Cancel reservation")
        print("4: List reservations")
        print("5: END\n")
        chosen = input("Choose option (enter a number 1-3): ")

        #CHECK TABLE SITUATION
        if (chosen == "1"):
            table_number, target_day, target_hour = get_params_from_user(
                False,
                "Enter the day you want to check, in format DD.MM.YYYY: ",
                False)
            if (target_day == None): continue
            print("\nTABLES SITUATION ON " + target_day.strftime("%d.%m.%Y") +
                  "\n")
            print("{:<9}".format("Table #"), end='')

            def header_action(iterated_hour):
                print("{:>8}".format(iterated_hour.strftime("%H:00")), end='')

            restaurant.loop_opening_hours(header_action)
            print("\n")

            tables = restaurant1.get_tables()
            for i in range(8):
                table = tables[i]
                reservations = table.get_reservations_for_day(target_day)
                print("{:<9}".format("Table " + str(i + 1)), end='')

                def row_action(iterated_hour):
                    reserved = False
                    for reservation in reservations:
                        res_date = reservation.get_date()
                        if (res_date.hour == iterated_hour.hour):
                            reserved = True
                            break
                    if (reserved): print("{:>8}".format("X"), end='')
                    else: print("{:>8}".format("FREE"), end='')

                restaurant.loop_opening_hours(row_action)
                print("\n")

        #RESERVE TABLES
        elif (chosen == "2"):
            table_number, target_day, date_hour = get_params_from_user(
                "Enter the number of the table you want to reserve (1-8): ",
                "Enter the day you want to reserve, in format DD.MM.YYYY: ",
                "Enter the hour you want to reserve (12-19), in format HH: ")
            if (table_number == None or target_day == None
                    or date_hour == None):
                continue
            table = restaurant1.get_tables()[table_number - 1]
            reservations = table.get_reservations_for_day(target_day)
            reserved = False
            for reservation in reservations:
                if (reservation.get_date().hour == int(date_hour.hour)):
                    reserved = True
                    break
            if (reserved):
                print(
                    "\nThis hour has already been reserved. Check the tables for availability.\n"
                )
            else:
                info = input(
                    "Enter your name to create a unique reservation: ")
                table.add_reservation(date_hour, info)
                print("\nA reservation was successfully created for " + info +
                      " in " + date_hour.strftime("%d.%m.%Y at %H:00") + "\n")

        #CANCEL RESERVATIONS
        elif (chosen == "3"):
            table_number, target_day, date_hour = get_params_from_user(
                "Enter the number of the table you want to cancel (1-8): ",
                "Enter the day you want to cancel, in format DD.MM.YYYY: ",
                "Enter the hour you want to cancel (12-19), in format HH: ")
            if (table_number == None or target_day == None
                    or date_hour == None):
                continue
            table = restaurant1.get_tables()[table_number - 1]
            reservations = table.get_reservations_for_day(target_day)
            target_reservation = None
            for reservation in reservations:
                if (reservation.get_date().hour == int(date_hour.hour)):
                    target_reservation = reservation
                    break
            if (target_reservation == None):
                print("\nThis time is not reserved.\n")
            else:
                name = input("Enter your name to confirm it's you: ")
                if (name != target_reservation.get_customer_info()):
                    print(
                        "\nThis name is not the same as the reservation. Cancelation cannot be done.\n"
                    )
                else:
                    table.remove_reservation(target_reservation)
                    print("\nThe reservation was successfully removed.\n")

        elif (chosen == "4"):
            table_number, target_day, date_hour = get_params_from_user(
                False,
                "Enter the day you want to list, in format DD.MM.YYYY: ",
                False)
            if (target_day == None): continue
            tables = restaurant1.get_tables()
            for table in tables:
                reservations = table.get_reservations_for_day(target_day)
                for reservation in reservations:
                    print(
                        "Table " + str(table.get_number()) + " - " +
                        str(reservation.get_date().strftime("%d.%m.%Y %H:00")))

        elif (chosen == "5"):
            save_restaurant_to_file(restaurant1)
            break

        else:
            print("\nThere is no option with input " + chosen +
                  ". Please try again.\n")
#!/usr/bin/env python3
import restaurant

my_restaurant = restaurant.Restaurant('Panda', 'Chinese')
print(my_restaurant.cuisine)
Esempio n. 15
0
    def __init__(self,
                 clients_number,
                 restaurants_number,
                 mutation_probability,
                 isDataProvided=False):
        self.cl = []
        self.rest = []
        self.workers = []
        self.clients_number = clients_number
        self.restaurants_number = restaurants_number
        self.mutation_probability = mutation_probability
        self.probability = []
        self.worst = []
        self.best = []
        self.workers_number = 0

        dtxt = []

        if not isDataProvided:
            for i in range(restaurants_number):
                self.rest.append(
                    restaurant.Restaurant(lower_distance=5,
                                          upper_distance=20,
                                          lower_cost=5,
                                          upper_cost=10))
            for i in range(clients_number):
                self.cl.append(client.Client(1, 5))

            for r in self.rest:
                dtxt.append([])
                for c in self.cl:
                    distance = random.randint(1, 20)
                    if distance <= r.max_distance:
                        r.clients[c] = distance
                        c.restaurants[r] = distance
                        dtxt[-1].append(distance)
                    else:
                        dtxt[-1].append(0)
            # for c in dtxt:
            #     print(c)
            # with open('distsData.txt', 'a') as f:
            #     for c in dtxt:
            #         for i in c:
            #             f.write(str(i)+"\t")
            #         f.write("\n")

        else:
            restsFile = open("restsData.txt")
            restsString = restsFile.read().split("\n")
            restsTable = []
            for r in restsString:
                restsTable.append(list(map(int, r.split("\t"))))
            for r in restsTable:
                self.rest.append(restaurant.Restaurant(r[0], r[1], r[2]))
            restsFile.close()

            clientsFile = open("clientsData.txt")
            clientsString = clientsFile.read().split("\n")
            clientsTable = []
            for c in clientsString:
                clientsTable.append(list(map(int, c.split("\t"))))
            for c in clientsTable:
                self.cl.append(client.Client(c[0], c[1], True))
            clientsFile.close()

            distsFile = open("distsData.txt")
            distsString = distsFile.read().split("\n")
            distsTable = []
            for d in distsString:
                l = list(map(int, d.split("\t")))
                distsTable.append(l)
            distsFile.close()
            for r in self.rest:
                for c in self.cl:
                    distance = distsTable[r.ID - 1][c.ID - 1]
                    if distance > 0:
                        r.clients[c] = distance
                        c.restaurants[r] = distance
Esempio n. 16
0
import restaurant
import table
import notificator
import datetime

new_rest = restaurant.Restaurant(name="Leto")
new_table = table.Table(seats_capacity=2,
                        shape='Rectangular',
                        coordinates=(50, 30),
                        dimensions=(20, 10))
new_notificator = notificator.Notificator(name="Hostess")
new_rest.add_table(new_table, 1)
iter_tables = new_rest.get_tables()
for table in iter_tables:
    print(table)
reservation_date = datetime.date(year=2018, month=5, day=17)
new_table.reserve(date=reservation_date,
                  notificator=new_notificator,
                  name="John",
                  email="*****@*****.**")
new_table.check_availability(date=reservation_date,
                             notificator=new_notificator)
new_table.cancel_reserve(reservation_date)
new_table.check_availability(date=reservation_date,
                             notificator=new_notificator)
Esempio n. 17
0
# 导入Restaurant类
import restaurant

# 实例
Haagen_Dazs = restaurant.IceCreamStand("Häagen-Dazs")
Haagen_Dazs.flavors = ['strawberry', 'chocolate', 'oreo']

Haagen_Dazs.describe_restaurant()
Haagen_Dazs.show_flavors()


chongqinghuoguo = restaurant.Restaurant("chongqinghuoguo", "hotpot")
chongqinghuoguo.describe_restaurant()
Esempio n. 18
0
import restaurant
import mesero
import os
marca_zapatera = os.sys.argv[1]
zapato_marca = os.sys.argv[2]
zap1 = mesero.Mesero(zapato_marca, 42, "cuero", "deportivo", 1200)
z1 = restaurant.Restaurant(marca_zapatera, zap1, "madera", 20, "americano")
print("restaurant:" + z1.getNombre())
print("mesero:" + zap1.getNombre())
z1.setMesero(zap1)
print(z1.cocinar())
Esempio n. 19
0
import restaurant

r1 = restaurant.Restaurant("Super", "French")

r1.describe()
Esempio n. 20
0
import restaurant

restaurant = restaurant.Restaurant('shi mao', '5 star')
restaurant.describe_restaurant()
Esempio n. 21
0
# -*- coding: utf-8 -*-
# filename: main_restaurant.py
# author: Kaishen
# date: 2019-5-24 23:24

# system import
import datetime

# customer import
import restaurant
''' 打印门店信息 '''
my_rest = restaurant.Restaurant('重庆小面', '面馆', 20)
my_rest.introduce()

# 设置工作时间
my_rest.showWorkTime(9)
my_rest.showWorkTime(23)
print()

# 更新就餐人数
my_rest.changeEatingPeople(10)

# 获取当前时间
now_time = datetime.datetime.now()
print(f'当前时间为 {now_time} ')
my_rest.showWorkTime(now_time.hour)
print()

my_rest.showTotalCustomers()
my_rest.changeEatingPeople(15)
my_rest.changeEatingPeople(12)
Esempio n. 22
0
# coding=utf-8

# 日期:2020-03-10
# 作者:YangZai
# 功能:导入Restaurant类

# 9-10 导入Restaurant类
import restaurant

my_restaurant = restaurant.Restaurant('老新亨手工面', '中餐馆')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
"""
9-10 Imported Restaurant: Using your latest Restaurant class, store it in
a module. Make a separate file that imports Restaurant. Make a Restaurant
instance, and call one of Restaurant's methods to show that the import 
statment is working properly.
"""

import restaurant
myRestaurant = restaurant.Restaurant("burger king", "fast")
myRestaurant.describe_restaurant()
Esempio n. 24
0
import restaurant as res

my_res1 = res.Restaurant('a_name', 'B_cusine')

my_res1.des_restaurant()
my_res1.open_restaurant()
"""
9-10. Imported Restaurant: Using your latest Restaurant class, store it in a  module. Make a separate file that imports Restaurant. Make a Restaurant instance, and call one of Restaurant’s methods to show that the import statement is working properly.
"""

import restaurant

new_restaurant = restaurant.Restaurant('Don Pepe', 'Pizza')

new_restaurant.open_restaurant()
new_restaurant.describe_restaurant()
Esempio n. 26
0
def main():
    my_restaurant = restaurant.Restaurant()

    my_simulation = simulate.Simulate(my_restaurant)
    my_simulation.run()
Esempio n. 27
0
##-------------------------------
# Cap.9 - Classes
# Python Crash Course
# Autor: Washington Candeia
##-------------------------------

# Faça você mesmo, p.249
# 9.10 - Importando Restaurant
import restaurant

restaurante = restaurant.Restaurant('roma', 'italiana')
restaurante.describe_restaurant()
Esempio n. 28
0
import restaurant

restaurant.Restaurant('Church Chicken', 'Fried food').describe_restaurant()
Esempio n. 29
0
import restaurant

res = restaurant.Restaurant("aa", ["bb"])

res.describe_restaurant()
Esempio n. 30
0
    managers = [
        people.Manager("Silly", "Seaborn", 12345),
        people.Manager("Sally", "Landborn", 64578),
        people.Manager("Sully", "Spaceborn", 11223)
    ]

    cooks = [
        people.Cook("Rikky", "Stormfire", 55794),
        people.Cook("Rukky", "Thunderfire", 5542)
    ]
    managers.extend(cooks)

    return managers


rest = restaurant.Restaurant()

rest.hall_dispatcher.workers_list.extend(populate_workers())

rest.hall_dispatcher.add_customer()
print("Making orders")
rest.hall_dispatcher.make_order()
rest.hall_dispatcher.make_order()
rest.hall_dispatcher.make_order()

print("\nGetting transaction history\n")
print(
    rest.get_transactions_history([
        datetime.datetime(year=2021, month=1, day=1),
        datetime.datetime(year=2022, month=1, day=1)
    ]))