1 задание
This commit is contained in:
commit
c80e837d44
235
1zadanie.py
Normal file
235
1zadanie.py
Normal file
@ -0,0 +1,235 @@
|
|||||||
|
# Практическая работа
|
||||||
|
# Тема: Обработка данных интернет-магазина
|
||||||
|
|
||||||
|
|
||||||
|
def load_products_from_file(filepath):
|
||||||
|
products = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
file = open(filepath, "r", encoding="utf-8")
|
||||||
|
|
||||||
|
for line in file:
|
||||||
|
line = line.strip()
|
||||||
|
|
||||||
|
if line == "":
|
||||||
|
continue
|
||||||
|
|
||||||
|
parts = line.split(";")
|
||||||
|
|
||||||
|
if len(parts) != 6:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
product = {
|
||||||
|
"id": int(parts[0]),
|
||||||
|
"name": parts[1],
|
||||||
|
"category": parts[2],
|
||||||
|
"price": float(parts[3]),
|
||||||
|
"quantity": int(parts[4]),
|
||||||
|
"description": parts[5]
|
||||||
|
}
|
||||||
|
products.append(product)
|
||||||
|
except:
|
||||||
|
continue
|
||||||
|
|
||||||
|
file.close()
|
||||||
|
|
||||||
|
except FileNotFoundError:
|
||||||
|
print("Файл не найден")
|
||||||
|
except:
|
||||||
|
print("Ошибка при чтении файла")
|
||||||
|
|
||||||
|
return products
|
||||||
|
|
||||||
|
|
||||||
|
def validate_product(product):
|
||||||
|
if "id" not in product:
|
||||||
|
return False
|
||||||
|
if "name" not in product:
|
||||||
|
return False
|
||||||
|
if "category" not in product:
|
||||||
|
return False
|
||||||
|
if "price" not in product:
|
||||||
|
return False
|
||||||
|
if "quantity" not in product:
|
||||||
|
return False
|
||||||
|
if "description" not in product:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if product["name"].strip() == "":
|
||||||
|
return False
|
||||||
|
if product["category"].strip() == "":
|
||||||
|
return False
|
||||||
|
if product["price"] < 0:
|
||||||
|
return False
|
||||||
|
if product["quantity"] < 0:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def filter_products_by_category(products, category):
|
||||||
|
result = []
|
||||||
|
|
||||||
|
for product in products:
|
||||||
|
if product["category"].lower() == category.lower():
|
||||||
|
result.append(product)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def search_products_by_keyword(products, keyword):
|
||||||
|
result = []
|
||||||
|
|
||||||
|
for product in products:
|
||||||
|
text = product["name"] + " " + product["description"]
|
||||||
|
|
||||||
|
if keyword.lower() in text.lower():
|
||||||
|
result.append(product)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def sort_products_by_price(products, descending=False):
|
||||||
|
return sorted(products, key=lambda x: x["price"], reverse=descending)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_discounted_price(price, discount_percent):
|
||||||
|
new_price = price - price * discount_percent / 100
|
||||||
|
return round(new_price, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def build_cart(products, product_ids):
|
||||||
|
cart = []
|
||||||
|
|
||||||
|
for product_id in product_ids:
|
||||||
|
for product in products:
|
||||||
|
if product["id"] == product_id:
|
||||||
|
cart.append(product)
|
||||||
|
break
|
||||||
|
|
||||||
|
return cart
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_cart_total(cart, discounts=None):
|
||||||
|
total = 0
|
||||||
|
|
||||||
|
for product in cart:
|
||||||
|
current_price = product["price"]
|
||||||
|
|
||||||
|
if discounts is not None:
|
||||||
|
if product["id"] in discounts:
|
||||||
|
current_price = calculate_discounted_price(current_price, discounts[product["id"]])
|
||||||
|
elif product["category"] in discounts:
|
||||||
|
current_price = calculate_discounted_price(current_price, discounts[product["category"]])
|
||||||
|
|
||||||
|
total += current_price
|
||||||
|
|
||||||
|
return round(total, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def group_products_by_category(products):
|
||||||
|
groups = {}
|
||||||
|
|
||||||
|
for product in products:
|
||||||
|
category = product["category"]
|
||||||
|
|
||||||
|
if category not in groups:
|
||||||
|
groups[category] = []
|
||||||
|
|
||||||
|
groups[category].append(product)
|
||||||
|
|
||||||
|
return groups
|
||||||
|
|
||||||
|
|
||||||
|
def generate_order_report(cart, total_cost):
|
||||||
|
report = "Отчет по заказу\n"
|
||||||
|
report += "-------------------------\n"
|
||||||
|
|
||||||
|
number = 1
|
||||||
|
for product in cart:
|
||||||
|
report += str(number) + ". " + product["name"] + " - " + str(product["price"]) + " руб.\n"
|
||||||
|
number += 1
|
||||||
|
|
||||||
|
report += "-------------------------\n"
|
||||||
|
report += "Количество товаров: " + str(len(cart)) + "\n"
|
||||||
|
report += "Итоговая стоимость: " + str(total_cost) + " руб.\n"
|
||||||
|
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
products = load_products_from_file("data.txt")
|
||||||
|
|
||||||
|
print("Загруженные товары:")
|
||||||
|
for product in products:
|
||||||
|
print(product)
|
||||||
|
|
||||||
|
valid_products = []
|
||||||
|
invalid_products = []
|
||||||
|
|
||||||
|
for product in products:
|
||||||
|
if validate_product(product):
|
||||||
|
valid_products.append(product)
|
||||||
|
else:
|
||||||
|
invalid_products.append(product)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("Корректных товаров:", len(valid_products))
|
||||||
|
print("Некорректных товаров:", len(invalid_products))
|
||||||
|
|
||||||
|
filtered_products = filter_products_by_category(valid_products, "Электроника")
|
||||||
|
print()
|
||||||
|
print("Товары категории Электроника:")
|
||||||
|
for product in filtered_products:
|
||||||
|
print(product["name"], "-", product["price"], "руб.")
|
||||||
|
|
||||||
|
found_products = search_products_by_keyword(valid_products, "игровой")
|
||||||
|
print()
|
||||||
|
print("Поиск по слову 'игровой':")
|
||||||
|
for product in found_products:
|
||||||
|
print(product["name"], "-", product["description"])
|
||||||
|
|
||||||
|
sorted_products = sort_products_by_price(found_products)
|
||||||
|
print()
|
||||||
|
print("После сортировки по цене:")
|
||||||
|
for product in sorted_products:
|
||||||
|
print(product["name"], "-", product["price"], "руб.")
|
||||||
|
|
||||||
|
if len(valid_products) > 0:
|
||||||
|
old_price = valid_products[0]["price"]
|
||||||
|
new_price = calculate_discounted_price(old_price, 10)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("Пример расчета скидки:")
|
||||||
|
print("Старая цена:", old_price)
|
||||||
|
print("Новая цена:", new_price)
|
||||||
|
|
||||||
|
cart = build_cart(valid_products, [1, 3, 5])
|
||||||
|
print()
|
||||||
|
print("Корзина:")
|
||||||
|
for product in cart:
|
||||||
|
print(product["name"], "-", product["price"], "руб.")
|
||||||
|
|
||||||
|
discounts = {
|
||||||
|
1: 10,
|
||||||
|
"Электроника": 5
|
||||||
|
}
|
||||||
|
|
||||||
|
total_cost = calculate_cart_total(cart, discounts)
|
||||||
|
print()
|
||||||
|
print("Итоговая стоимость корзины:", total_cost, "руб.")
|
||||||
|
|
||||||
|
groups = group_products_by_category(valid_products)
|
||||||
|
print()
|
||||||
|
print("Группировка товаров по категориям:")
|
||||||
|
for category in groups:
|
||||||
|
print(category, "-", len(groups[category]), "товаров")
|
||||||
|
|
||||||
|
report = generate_order_report(cart, total_cost)
|
||||||
|
print()
|
||||||
|
print(report)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
6
data.txt
Normal file
6
data.txt
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
1;Ноутбук Lenovo;Электроника;55000;10;Игровой ноутбук с мощной видеокартой
|
||||||
|
2;Мышь Logitech;Электроника;2500;25;Беспроводная мышь для работы
|
||||||
|
3;Клавиатура Redragon;Электроника;3200;15;Механическая игровая клавиатура
|
||||||
|
4;Рюкзак Xiaomi;Аксессуары;2800;12;Городской рюкзак для ноутбука
|
||||||
|
5;Наушники JBL;Электроника;4700;8;Беспроводные наушники с хорошим звуком
|
||||||
|
6;Блокнот;Канцтовары;150;40;Тетрадь для записей
|
||||||
0
requirements.txt
Normal file
0
requirements.txt
Normal file
Loading…
Reference in New Issue
Block a user