Проект по анализу онлайн-магазина 👩💻
#Python
Структура проекта
data_preprocessing.py
Этот файл будет содержать функции для предобработки данных
model_training.py
Этот файл будет содержать функции для обучения модели
api.py
Этот файл будет содержать код для реализации API
run.py
Этот файл запускает Flask-приложение
👩💻 Для запуска следуйте инструкции: run.py
#Python
Структура проекта
project/
│
├── data/
│ └── user_actions.csv
│
├── app/
│ ├── __init__.py
│ ├── data_preprocessing.py
│ ├── model_training.py
│ ├── api.py
│
└── run.py
data_preprocessing.py
Этот файл будет содержать функции для предобработки данных
# app/data_preprocessing.py
import pandas as pd
def load_and_preprocess_data(filepath):
data = pd.read_csv(filepath)
data['visit_time'] = pd.to_datetime(data['visit_time'])
data['visit_day'] = data['visit_time'].dt.day
data['visit_hour'] = data['visit_time'].dt.hour
data = pd.get_dummies(data, columns=['traffic_source'])
data['time_since_last_visit'] = data.groupby('user_id')['visit_time'].diff().dt.total_seconds().fillna(0)
return data
model_training.py
Этот файл будет содержать функции для обучения модели
# app/model_training.py
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import accuracy_score
def train_model(data):
X = data.drop(columns=['user_id', 'visit_time', 'purchases'])
y = data['purchases']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = GradientBoostingClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
return model, accuracy
api.py
Этот файл будет содержать код для реализации API
# app/api.py
from flask import Flask, request, jsonify
import pandas as pd
from app.data_preprocessing import load_and_preprocess_data
from app.model_training import train_model
app = Flask(__name__)
# Загрузим и предобработаем данные
data = load_and_preprocess_data('data/user_actions.csv')
model, accuracy = train_model(data)
@app.route('/predict', methods=['POST'])
def predict():
user_data = request.get_json()
user_df = pd.DataFrame([user_data])
user_df['visit_time'] = pd.to_datetime(user_df['visit_time'])
user_df['visit_day'] = user_df['visit_time'].dt.day
user_df['visit_hour'] = user_df['visit_time'].dt.hour
user_df = pd.get_dummies(user_df, columns=['traffic_source'])
for col in data.drop(columns=['user_id', 'visit_time', 'purchases']).columns:
if col not in user_df.columns:
user_df[col] = 0
prediction = model.predict_proba(user_df)[:, 1]
return jsonify({'purchase_probability': prediction[0]})
if __name__ == '__main__':
app.run(debug=True)
run.py
Этот файл запускает Flask-приложение
# run.py
from app.api import app
if __name__ == '__main__':
app.run(debug=True)
Please open Telegram to view this post
VIEW IN TELEGRAM
Запуск проекта по анализу онлайн-магазина 👩💻
Установка зависимостей:
Запустите Flask-приложение командой:
Используйте инструмент вроде Postman или отправьте POST-запрос с помощью curl для тестирования API.
Пример запроса с помощью curl:
Установка зависимостей:
pip install pandas scikit-learn flask
Запустите Flask-приложение командой:
python run.py
Используйте инструмент вроде Postman или отправьте POST-запрос с помощью curl для тестирования API.
Пример запроса с помощью curl:
curl -X POST http://127.0.0.1:5000/predict -H "Content-Type: application/json" -d '{
"visit_time": "2023-07-01 12:34:56",
"page_views": 5,
"time_on_site": 300,
"add_to_cart": 1,
"traffic_source": "search"
}'Please open Telegram to view this post
VIEW IN TELEGRAM
Скрабер ключевых слов на Python
#Python
Вот так все просто😳
#Python
import string
from collections import Counter
def keyword_scraper(filename, threshold):
"""
Скрабер ключевых слов из текстового файла с фильтрацией редких слов.
:param filename: Имя текстового файла.
:param threshold: Порог частоты слов для их включения в вывод.
:return: None
"""
try:
with open(filename, 'r') as file: # Открываем и читаем файл
text = file.read()
text = text.lower() # Приводим текст к нижнему регистру
translator = str.maketrans('', '', string.punctuation) # Удаляем знаки препинания
text = text.translate(translator)
words = text.split() # Разбиваем текст на слова
word_counts = Counter(words) # Считаем количество вхождений каждого слова
filtered_word_counts = {word: count for word, count in word_counts.items() if count >= threshold} # Фильтруем слова по порогу частоты
sorted_word_counts = sorted(filtered_word_counts.items(), key=lambda item: item[1], reverse=True) # Сортируем слова по убыванию частоты
for word, count in sorted_word_counts: # Выводим результат
print(f'{word}: {count}')
except FileNotFoundError:
print(f"Файл {filename} не найден.")
except Exception as e:
print(f"Произошла ошибка: {e}")
# Пример использования
keyword_scraper('example.txt', 2)
Вот так все просто
Please open Telegram to view this post
VIEW IN TELEGRAM
Генератор ключей шифрования 👩💻
#pythone
#pythone
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
def generate_keys():
# Генерация приватного ключа
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
# Генерация публичного ключа из приватного
public_key = private_key.public_key()
# Сериализация приватного ключа
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword')
)
# Сериализация публичного ключа
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# Сохранение ключей в файлы
with open('private_key.pem', 'wb') as private_file:
private_file.write(private_pem)
with open('public_key.pem', 'wb') as public_file:
public_file.write(public_pem)
print("Ключи успешно сгенерированы и сохранены в файлы private_key.pem и public_key.pem")
if __name__ == "__main__":
generate_keys()
Please open Telegram to view this post
VIEW IN TELEGRAM
import time
# Функция для линейного поиска
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
# Функция для бинарного поиска
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Генерация большого массива
import random
large_arr = random.sample(range(1, 100000000), 10000000) # Массив из 10000000 уникальных чисел
target = large_arr[random.randint(0, 9999999)] # Случайный элемент из массива
# Время выполнения линейного поиска
start_time = time.time()
linear_search(large_arr, target)
end_time = time.time()
print(f"Линейный поиск занял: {end_time - start_time:.6f} секунд")
# Время выполнения бинарного поиска
large_arr.sort() # Сортировка массива
start_time = time.time()
binary_search(large_arr, target)
end_time = time.time()
print(f"Бинарный поиск занял: {end_time - start_time:.6f} секунд")
Для сравнения 😎
Линейный поиск занял: 0.236526 секунд
Бинарный поиск занял: 0.000000 секунд
Please open Telegram to view this post
VIEW IN TELEGRAM
import random
import datetime
# Определим знаки зодиака
zodiac_signs = {
"Овен": (datetime.date(2023, 3, 21), datetime.date(2023, 4, 19)),
"Телец": (datetime.date(2023, 4, 20), datetime.date(2023, 5, 20)),
"Близнецы": (datetime.date(2023, 5, 21), datetime.date(2023, 6, 20)),
"Рак": (datetime.date(2023, 6, 21), datetime.date(2023, 7, 22)),
"Лев": (datetime.date(2023, 7, 23), datetime.date(2023, 8, 22)),
"Дева": (datetime.date(2023, 8, 23), datetime.date(2023, 9, 22)),
"Весы": (datetime.date(2023, 9, 23), datetime.date(2023, 10, 22)),
"Скорпион": (datetime.date(2023, 10, 23), datetime.date(2023, 11, 21)),
"Стрелец": (datetime.date(2023, 11, 22), datetime.date(2023, 12, 21)),
"Козерог": (datetime.date(2023, 12, 22), datetime.date(2024, 1, 19)),
"Водолей": (datetime.date(2024, 1, 20), datetime.date(2024, 2, 18)),
"Рыбы": (datetime.date(2024, 2, 19), datetime.date(2024, 3, 20))
}
# Наборы фраз для генерации гороскопов
beginnings = [
"Сегодня вас ждет", "На вашем пути будет", "Ожидайте",
"Готовьтесь к", "День принесет вам"
]
middles = [
"неожиданное событие,", "приятная встреча,", "интересное предложение,",
"новая возможность,", "вдохновляющий момент,"
]
ends = [
"которое изменит ваше представление о жизни.",
"которое подарит вам много положительных эмоций.",
"которое потребует от вас решительности.",
"которое укрепит ваши отношения с близкими.",
"которое принесет вам финансовую выгоду."
]
# Функция для генерации уникального гороскопа
def generate_horoscope():
return f"{random.choice(beginnings)} {random.choice(middles)} {random.choice(ends)}"
# Функция для получения гороскопа по периоду
def get_horoscope(period):
horoscopes = {
"день": generate_horoscope(),
"месяц": generate_horoscope(),
"год": generate_horoscope()
}
return horoscopes.get(period.lower(), "Неверный период")
# Основная функция
def main():
sign = input("Введите ваш знак зодиака: ").title()
if sign not in zodiac_signs:
print("Неверный знак зодиака.")
return
period = input("Гороскоп на (день, месяц, год): ").lower()
horoscope = get_horoscope(period)
print(f"{sign}: {horoscope}")
if __name__ == "__main__":
main()
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
viselitsya.py
5.2 KB
Игра Виселица на #Python 👩💻
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
tommy.py
6.1 KB
Please open Telegram to view this post
VIEW IN TELEGRAM
Решаем задачу:
Как-то так:
#Python
У вас бесконечный запас воды и два ведра — на 5 литров и 3 литра. Вопрос: Как вы отмерите 4 литра?
Как-то так:
from collections import deque
import math
def solve_water_jug(a_cap, b_cap, target):
# Проверка разрешимости
if target > max(a_cap, b_cap):
return "Невозможно: цель больше любого ведра"
if target % math.gcd(a_cap, b_cap) != 0:
return "Невозможно: НОД не делит целевой объём"
# BFS очередь: (состояние, путь)
queue = deque([((0, 0), [(0, 0)])])
visited = set()
visited.add((0, 0))
while queue:
(a, b), path = queue.popleft()
# Проверка цели
if a == target or b == target:
return path
next_states = []
# 1. Заполнить A
next_states.append((a_cap, b))
# 2. Заполнить B
next_states.append((a, b_cap))
# 3. Опустошить A
next_states.append((0, b))
# 4. Опустошить B
next_states.append((a, 0))
# 5. Перелить из A в B
pour = min(a, b_cap - b)
next_states.append((a - pour, b + pour))
# 6. Перелить из B в A
pour = min(b, a_cap - a)
next_states.append((a + pour, b - pour))
for state in next_states:
if state not in visited:
visited.add(state)
queue.append((state, path + [state]))
return "Решение не найдено"
# Пример: классическая задача — получить 4 литра из 5 и 3
solution = solve_water_jug(5, 3, 4)
for step in solution:
print(step)
#Python
#photoprompt
copy then👇🏻
copy then👇🏻
A side-profile portrait framed from the chest up, captured against a dark, minimal background with a focused beam of cool light illuminating the subject. The lighting is low-key and directional, coming from the upper rear right at a cool temperature (~5000K), creating a striking rim light along the face, headphones, and jacket edges while leaving the rest of the composition in deep shadow. The background transitions smoothly from near-black to soft gray tones (approx. HEX #0A0E12 to #1E2227), with a faint diagonal light streak adding depth and atmosphere. The subject wears a dark, matte-textured jacket with subtle highlights emphasizing its structure, and large over-ear headphones in metallic or matte silver tones with faint reflections on their surface. The pose is neutral and composed, with the face slightly tilted forward, conveying focus and introspection. Use a simulated 85mm lens at f/2.0 for shallow depth of field and precise subject isolation, capturing clean textures and controlled light falloff. The overall aesthetic is cinematic and modern, combining minimalist composition with moody, high-contrast lighting for a sleek, futuristic editorial tone. Editorial, modern, high-detail, cinematic composition, ultra-realistic textures, professional fashion photography style.
🔥2❤1
#photoprompt
copy then👇🏻
copy then👇🏻
Create a bold, stylized half-length portrait of the person from the input photo, captured from a low-angle upward-facing perspective, with the head tilted back slightly and the face illuminated from below. The subject wears a high-neck garment (e.g., ribbed turtleneck) and large, glossy sunglasses that reflect stylized neon light. The lighting is highly directional and graphic: use deep blue ambient fill with hard hot pink key lighting that casts sharp, unnatural gradients across the face, sunglasses, and clothing, creating a posterized or vector-like glow. The background is a pure, uninterrupted black (#000000), with no visual distractions — enhancing the isolation and intensity of the subject. Simulate a telephoto lens (85–135mm) at f/2.0 for high subject clarity with natural compression. Reflections on the glasses should dominate the upper part of the image, possibly with abstract neon shapes or color blocks. The skin texture is softly stylized or semi-synthetic, and shadows fall off steeply. The final aesthetic is cyber-noir, editorial, posterized, and ultra-minimalist, evoking digital anonymity, power, and cool detachment.
🔥2❤1
#photoprompt
copy then👇🏻
copy then👇🏻
A mid-shot portrait framed from the chest up, featuring a minimalist, high-contrast lighting setup that creates a striking dual-tone color effect. The composition centers the subject against a completely dark background (approx. HEX #06060A), enhancing isolation and mood. The lighting is strongly directional — a deep red key light (~2200K) from the right and a cool cyan-blue fill (~6000K) from the left — producing a dramatic chromatic split across the face and neck. The color palette is dominated by rich reds, deep shadows, and cool blue highlights, creating a cinematic balance between warmth and coldness. The subject’s clothing is simple and matte, typically a dark shirt that absorbs light and keeps focus on facial contours. The expression is calm, introspective, and slightly detached, enhancing the atmospheric intensity. Use a simulated 85mm lens at f/1.8 for shallow depth of field, ensuring sharp focus on facial features while allowing smooth gradient falloff into the shadows. The overall aesthetic is moody, modern, and futuristic — blending fashion minimalism with cyber-noir lighting. Editorial, modern, high-detail, cinematic composition, ultra-realistic textures, professional fashion photography style.
❤1🔥1
#photoprompt
copy then👇🏻
copy then👇🏻
A close-up portrait framed from the chest up, set in an urban night environment illuminated by bold neon lighting. The subject stands slightly turned to the side with a composed, confident expression, wearing reflective sunglasses that capture the surrounding neon signs. The lighting is dual-toned and cinematic — a deep red key light (~2500K) from one side and a contrasting cyan-blue fill (~5500K) from the opposite, creating sculptural definition and a cyberpunk-inspired chromatic contrast across the face and clothing. The background features softly blurred neon panels and bokeh lights in red and blue hues (approx. HEX #E6003A to #009FE3), providing depth and atmosphere. The outfit consists of a dark, matte or leather-textured jacket with structured folds that catch subtle reflections from the colored lights, emphasizing texture and contour. The overall palette is moody and saturated, blending urban futurism with editorial polish. Use a simulated 85mm lens at f/1.8 for shallow depth of field and cinematic subject isolation, ensuring high clarity on the illuminated edges while maintaining soft background diffusion. The mood is sleek, mysterious, and modern — merging high-fashion edge with cyber-noir lighting. Editorial, modern, high-detail, cinematic composition, ultra-realistic textures, professional fashion photography style.
❤1👍1🔥1