ch
Feedback
Python/ django

Python/ django

前往频道在 Telegram

📈 Telegram 频道 Python/ django 的分析概览

频道 Python/ django (@pythonl) 俄语 语言赛道中的 是活跃参与者。目前社区聚集了 59 990 名订阅者,在 技术与应用 类别中位列第 2 205,并在 俄罗斯 地区排名第 10 243

📊 受众指标与增长动态

невідомо 创建以来,项目保持高速增长,吸引了 59 990 名订阅者。

根据 12 六月, 2026 的最新数据,频道保持稳定运转。过去 30 天订阅人数变化为 -567,过去 24 小时变化为 -11,整体触达仍然可观。

  • 认证状态: 未认证
  • 互动率 (ER): 平均受众互动率为 7.01%。内容发布后 24 小时内通常能获得 3.19% 的反应,占订阅者总量。
  • 帖子覆盖: 每篇帖子平均可获得 4 203 次浏览,首日通常累积 1 913 次浏览。
  • 互动与反馈: 受众积极参与,单帖平均反应数为 22
  • 主题关注点: 内容集中在 github, claude, контекст, архитектура, api 等核心主题上。

📝 描述与内容策略

作者将该频道定位为表达主观观点的平台:
по всем вопросам @haarrp @itchannels_telegram - 🔥 все ит каналы @ai_machinelearning_big_data -ML @ArtificialIntelligencedl -AI @datascienceiot - 📚 @pythonlbooks РКН: clck.ru/3Fmxm...

凭借高频更新(最新数据采集于 13 六月, 2026),频道始终保持新鲜度与高覆盖。分析显示受众积极互动,使其成为 技术与应用 类别中的关键影响点。

59 990
订阅者
-1124 小时
-1197
-56730
帖子存档
Top 6 Algorithms Every Software Engineer Should Know💲 Топ-6 алгоритмов, которые должен знать каждый инженер-программист. 1)
+5
Top 6 Algorithms Every Software Engineer Should Know💲 Топ-6 алгоритмов, которые должен знать каждый инженер-программист. 1) Binary Search Algorithm. 2) Bubble Sort Algorithm. 3) Merge Sort Algorithm 4) Depth-first Search Algorithm 5) Dijkstra’s Algorithm 6) Randomized Algorithm @pythonl

🦸‍♂Python DSA шпаргалка для супергероев ▪ List Methods изображение 2. ▪ Dictionary Operations изображение 3. ▪ Dictionary me
+5
🦸‍♂Python DSA шпаргалка для супергероевList Methods изображение 2.Dictionary Operations изображение 3.Dictionary methods изображение 4.Set Operations изображение 5. String Methods изображение 6. @pythonl

🔥 Подборка обучающих каналов для программистов. 🖥 Machine learning ai_ml – крупнейши канал по ии, нейросетям и науке о данных. datasc - дата сайнс обучение самой востребованной профессии. @bigdatai - Big Data @machinelearning_ru – гайды по машинному обучению @machinelearning_interview – подготовка к собеседованию мл. @datascienceiot – бесплатные книги ds @ArtificialIntelligencedl – ИИ @machinee_learning – чат о машинном обучении @datascienceml_jobs - вакансии ds, ml @Machinelearning_Jobs - чат с вакансиями 🖥 Python @pythonl - крупнейший канал для Python программистов. @pro_python_code – учим python с ментором. @python_job_interview – подготовка к Python собеседованию. @python_testit - проверочные тесты на python @pythonlbooks - современные книги Python @python_djangojobs - работа для Python программистов @python_django_work - чат обсуждения вакансий #️⃣ c# C# - канал для изучения C# на практике. @csharp_cplus - C# чат @csharp_1001_notes - инструменты C# 🖥 C++ @cpluspluc - C++ кодинг 🖥 SQL базы данных @sqlhub - Повышение эффективности кода с грамотным использованием бд. @chat_sql - чат изучения бд. 👣 Golang @Golang_google - восхитительный язык от Google, мощный и перспективный. @golang_interview - вопросы и ответы с собеседований по Go. Для всех уровней разработчиков. @golangtests - интересные тесты и задачи GO @golangl - чат изучающих Go @GolangJobsit - отборные вакансии и работа GO @golang_jobsgo - чат для ищущих работу. @golang_books - полезные книги Golang @golang_speak - обсуждение языка Go @golangnewss - новости go 🖥 Linux linux - kali linux ос для хакинга linux chat - чат linux для обучения и помощи. @linux_read - бесплатные книги linux 🖥 Javascript / front @react_tg - - 40,14% разработчиков сайтов использовали React в 2022 году - это самая популярная библиотека для создания сайтов. @javascript -канал для JS и FrontEnd разработчиков. Лучшие практики и примеры кода. Туториалы и фишки JS @Js Tests - каверзные тесты JS @hashdev - погружение в web разработку. @javascriptjobjs - отборные вакансии и работа FrontEnd. @jsspeak - чат поиска FrontEnd работы. 🖥 Java @javatg - выучить Java с senior разработчиком на практике @javachats - чат для ответов на вопросы по Java @java_library - библиотека книг Java @android_its - Android разработка @java_quizes - тесты Java @Java_workit - работа Java @progersit - шпаргалки ит 👷‍♂️ IT работа https://t.me/addlist/_zyy_jQ_QUsyM2Vi -ит каналы по яп с вакансиями 🤡It memes @memes_prog - ит-мемы ⚙️ Rust @rust_code - Rust избавлен от болевых точек, которые есть во многих современных яп @rust_chats - чат rust 📓 Книги https://t.me/addlist/HwywK4fErd8wYzQy - актуальные книги по всем яп ⭐️ Нейронные сети @vistehno - chatgpt ведет блог, решает любые задачи и отвечает на любые ваши вопросы. @aigen - сети для генерации картинок. видео, музыки и многого другого. @neural – погружение в нейросети. 📢 English for coders @english_forprogrammers - Английский для программистов 🖥PHP @phpshka - PHP академия для программистов. 🖥 Devops Devops - канал для DevOps специалистов. 🔥 Папки для программитов https://t.me/addlist/_FjtIq8qMhU0NTYy - машинное обучение, нейросети, глубокое обучение https://t.me/addlist/eEPya-HF6mkxMGIy - папка для Python разработчиков https://t.me/addlist/MUtJEeJSxeY2YTFi - папка для Golang разработчиков

🚀 Pairing Telegram data with Python. Read and analyze chat messages Парсим данные в Telegram на Python. Читаем и анализируем сообщения из чатов. from xmlrpc.client import DateTime from telethon.sync import TelegramClient from telethon.tl.functions.messages import GetDialogsRequest from telethon.tl.types import InputPeerEmpty from telethon.tl.functions.messages import GetHistoryRequest from telethon.tl.types import PeerChannel import csv api_id = 'api id' api_hash = "api_hash" phone = "phone number" client = TelegramClient(phone, api_id, api_hash) client.start() chats = [] last_date = None chunk_size = 200 groups=[] result = client(GetDialogsRequest( offset_date=last_date, offset_id=0, offset_peer=InputPeerEmpty(), limit=chunk_size, hash = 0 )) chats.extend(result.chats) for chat in chats: try: if chat.megagroup== True: groups.append(chat) except: continue print("Выберите группу для парсинга сообщений и членов группы:") i=0 for g in groups: print(str(i) + "- " + g.title) i+=1 g_index = input("Введите нужную цифру: ") target_group=groups[int(g_index)] print("Узнаём пользователей...") all_participants = [] all_participants = client.get_participants(target_group) print("Сохраняем данные в файл...") with open("members.csv", "w", encoding="UTF-8") as f: writer = csv.writer(f,delimiter=",",lineterminator="\n") writer.writerow(["username", "name","group"]) for user in all_participants: if user.username: username= user.username else: username= "" if user.first_name: first_name= user.first_name else: first_name= "" if user.last_name: last_name= user.last_name else: last_name= "" name= (first_name + ' ' + last_name).strip() writer.writerow([username,name,target_group.title]) print("Парсинг участников группы успешно выполнен.") offset_id = 0 limit = 100 all_messages = [] total_messages = 0 total_count_limit = 0 while True: history = client(GetHistoryRequest( peer=target_group, offset_id=offset_id, offset_date=None, add_offset=0, limit=limit, max_id=0, min_id=0, hash=0 )) if not history.messages: break messages = history.messages for message in messages: all_messages.append(message.message) offset_id = messages[len(messages) - 1].id if total_count_limit != 0 and total_messages >= total_count_limit: break print("Сохраняем данные в файл...") with open("chats.csv", "w", encoding="UTF-8") as f: writer = csv.writer(f, delimiter=",", lineterminator="\n") for message in all_messages: writer.writerow([message]) print('Парсинг сообщений группы успешно выполнен.') @pythonl

Building an Image Recognition API using Flask Создание API для распознавания изображений с помощью Flask. Шаг 1: Настройка ср
+5
Building an Image Recognition API using Flask Создание API для распознавания изображений с помощью Flask. Шаг 1: Настройка среды проекта 1. Создайте новый каталог для вашего проекта и перейдите в него. 2. Создайте виртуальную среду (необязательно, но рекомендуется): (Изображение 1.) 3. Установите необходимые библиотеки (изображение 2.) Шаг 2: Создайте веб-приложение Flask Создайте новый файл с именем app.py в каталоге проекта (изображение 3.) Шаг 3: Запустите приложение Flask Сохраните изменения и запустите приложение Flask (изображение 4.) Шаг 4: Протестируйте API Теперь ваш API запущен, и вы можете отправлять изображения на адрес /predict с помощью HTTP POST запросов. Для тестирования API можно использовать такие инструменты, как curl или Postman. Пример использования curl (изображение 5.) Пример с использованием запросов Python (изображение 6.) @pythonl

🕸 Python Web Scraping Этот исчерпывающий список содержит библиотеки python, связанные с веб-парсингом и обработкой данных. W
🕸 Python Web Scraping Этот исчерпывающий список содержит библиотеки python, связанные с веб-парсингом и обработкой данных. Web Scraping: Frameworks scrapy - web-scraping framework (twisted based). pyspider - A powerful spider system. autoscraper - A smart, automatic and lightweight web scraper grab - web-scraping framework (pycurl/multicurl based) ruia - Async Python 3.6+ web scraping micro-framework based on asyncio cola - A distributed crawling framework. frontera - A scalable frontier for web crawlers dude - A simple framework for writing web scrapers using decorators. ioweb - Web scraping framework based on gevent and lxml Web Scraping : Tools portia - Visual scraping for Scrapy. restkit - HTTP resource kit for Python. It allows you to easily access to HTTP resource and build objects around it. requests-html - Pythonic HTML Parsing for Humans. ScrapydWeb - A full-featured web UI for Scrapyd cluster management, which supports Scrapy Log Analysis & Visualization, Auto Packaging, Timer Tasks, Email Notice and so on. Starbelly - Starbelly is a user-friendly and highly configurable web crawler front end. Gerapy - Distributed Crawler Management Framework Based on Scrapy, Scrapyd, Django and Vue.js Web Scraping : Bypass Protection cloudscraper - A Python module to bypass Cloudflare's anti-bot page. ▪ GIthub @pythonl

🐍 10 Useful python scripts 10 интересных скриптов Python. • Создавайте веб-бота # pip install selenium import time from selenium import webdriver from selenium.webdriver.common.keys import Keysbot = webdriver.Chrome("chromedriver.exe") bot.get('http://www.google.com') search = bot.find_element_by_name('q') search.send_keys("@codedev101") search.send_keys(Keys.RETURN) time.sleep(5) bot.quit() • Улучшение изображений на Python # pip install pillow from PIL import Image,ImageFilter from PIL import ImageEnhance im = Image.open('img.jpg') # Choose your filter # add Hastag at start if you don't want to any filter below en = ImageEnhance.Color(im) en = ImageEnhance.Contrast(im) en = ImageEnhance.Brightness(im) en = ImageEnhance.Sharpness(im)# result en.enhance(1.5).show("enhanced") • Парсинг текстов песен # pip install lyricsgenius import lyricsgenius api_key = "xxxxxxxxxxxxxxxxxxxxx" genius = lyricsgenius.Genius(api_key) artist = genius.search_artist("Pop Smoke", max_songs=5,sort="title") song = artist.song("100k On a Coupe") print(song.lyrics)Получение данных Exif для фотографий # Get Exif of Photo # Method 1 # pip install pillow import PIL.Image import PIL.ExifTags img = PIL.Image.open("Img.jpg") exif_data = { PIL.ExifTags.TAGS[i]: j for i, j in img._getexif().items() if i in PIL.ExifTags.TAGS } print(exif_data) # Method 2 # pip install ExifRead import exifread filename = open(path_name, 'rb') tags = exifread.process_file(filename) print(tags) Поиск в Google # pip install google from googlesearch import search query = "Medium.com" for url in search(query): print(url) Преобразование: шестнадцатеричная система в RGB # Conversion: Hex to RGB def Hex_to_Rgb(hex): h = hex.lstrip('#') return tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) print(Hex_to_Rgb('#c96d9d')) # (201, 109, 157) print(Hex_to_Rgb('#fa0515')) # (250, 5, 21) Конвертация фотографий в формат Cartonize # pip install opencv-python import cv2 img = cv2.imread('img.jpg') grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) grayimg = cv2.medianBlur(grayimg, 5) edges = cv2.Laplacian(grayimg , cv2.CV_8U, ksize=5) r,mask =cv2.threshold(edges,100,255,cv2.THRESH_BINARY_INV) img2 = cv2.bitwise_and(img, img, mask=mask) img2 = cv2.medianBlur(img2, 5) cv2.imwrite("cartooned.jpg", mask) Тестирование скорости соединения с помощью Python. # pip install pyspeedtest # pip install speedtest # pip install speedtest-cli #method 1 import speedtest speedTest = speedtest.Speedtest() print(speedTest.get_best_server()) #Check download speed print(speedTest.download()) #Check upload speed print(speedTest.upload()) # Method 2 import pyspeedtest st = pyspeedtest.SpeedTest() st.ping() st.download() st.upload() Проверка состояния сайта # pip install requests #method 1 import urllib.request from urllib.request import Request, urlopenreq = Request('https://medium.com/@pythonians', headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).getcode() print(webpage) # 200 # method 2 import requests r = requests.get("https://medium.com/@pythonians") print(r.status_code) # 200 Извлечение текста OCR из изображений # pip install pytesseract import pytesseract from PIL import Image pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' t=Image.open("img.png") text = pytesseract.image_to_string(t, config='') print(text) @pythonl

🖥 Create a Mock SQL DB in Python from CSV for unit testing Создание макета SQL-базы данных в Python из CSV для модульного те
🖥 Create a Mock SQL DB in Python from CSV for unit testing Создание макета SQL-базы данных в Python из CSV для модульного тестирования. pip install pandas pip install sqlglot pip install sqlalchemy from sqlalchemy import create_engine, text import sqlglot import pandas as pd def execute_sql_query(sql): query_as_sqlite = sqlglot.transpile(sql, read="postgres", write="sqlite")[0] mocked_db = create_engine('sqlite://') pd.read_csv('data.csv').to_sql('table_name', con=mocked_db) with mocked_db.connect() as connection: result = connection.execute(text(query_as_sqlite)) return result @pythonl

Machine learning — обучающий для тех, кто хочет погрузится в волшебный мир Нейронауки! Нейронные сети, машинное обучение, Data Science, изучаем базу, объясняем код, изучаем лучшие проекты, выкладываем бесплатные курсы и книги из области Машинного обучения. Начать учиться

🔭 Daily Useful Scripts Daily.py is a repository that provides a collection of ready-to-use Python scripts for automating com
🔭 Daily Useful Scripts Daily.py is a repository that provides a collection of ready-to-use Python scripts for automating common daily tasks. Daily.py - это репозиторий, который предоставляет коллекцию готовых к запуску скриптов Python для автоматизации обычных повседневных задач. git clone https://github.com/Chamepp/Daily.py.gitGithub @pythonl

https://t.me/backend_architecture Канал для тех, кто интересуется архитектурой программного обеспечения, оптимизацией произво
https://t.me/backend_architecture Канал для тех, кто интересуется архитектурой программного обеспечения, оптимизацией производительности систем, масштабируемостью, надежностью и другими аспектами разработки программного обеспечения. Канал подойдет тем, кто хочет улучшить свои навыки и знания в области backend разработки и system design. 📌 Backend-разработка 📌 System Design 📌 Архитектура 📌 Проектирование https://t.me/backend_architecture

💼Building a Trading Strategy with Machine Learning Models and Yahoo Finance in Python. Создаем алгоритм для торговли с помощью моделей машинного обучения и Yahoo Finance на Python. import yfinance as yf import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer import matplotlib.pyplot as plt # Step 1: Data Collection ticker = "AAPL" start_date = "2021-01-01" end_date = "2023-01-06" data = yf.download(ticker, start=start_date, end=end_date, progress=False) # Step 2: Data Preprocessing data["Return"] = data["Close"].pct_change() data.dropna(inplace=True) # Step 3: Feature Engineering data["SMA_5"] = data["Close"].rolling(window=5).mean() data["SMA_20"] = data["Close"].rolling(window=20).mean() # Step 4: Model Selection and Training X = data[["SMA_5", "SMA_20"]] y = (data["Return"] > 0).astype(int) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) pipeline = Pipeline([ ('imputer', SimpleImputer(strategy='mean')), ('classifier', RandomForestClassifier(n_estimators=100, random_state=42)) ]) pipeline.fit(X_train, y_train) # Step 5: Model Evaluation y_pred_train = pipeline.predict(X_train) train_accuracy = accuracy_score(y_train, y_pred_train) y_pred_test = pipeline.predict(X_test) test_accuracy = accuracy_score(y_test, y_pred_test) print("Train Accuracy:", train_accuracy) print("Test Accuracy:", test_accuracy) # Step 6: Strategy Design data["Predicted_Return"] = pipeline.predict(X) data["Signal"] = data["Predicted_Return"].diff() data.loc[data["Signal"] > 0, "Position"] = 1 data.loc[data["Signal"] < 0, "Position"] = -1 data["Position"].fillna(0, inplace=True) # Step 7: Backtesting data["Strategy_Return"] = data["Position"] * data["Return"] cumulative_returns = (data["Strategy_Return"] + 1).cumprod() plt.figure(figsize=(10, 6)) plt.plot(data.index, cumulative_returns) plt.xlabel("Date") plt.ylabel("Cumulative Returns") plt.title("Trading Strategy Performance") plt.grid(True) plt.show() @pythonl

🖥 10 Advanced Python Scripts For Everyday Programming 10 полезных скриптов Python для повседневных задач 1. SpeedTest with Python # pip install pyspeedtest # pip install speedtest # pip install speedtest-cli #method 1 import speedtest speedTest = speedtest.Speedtest() print(speedTest.get_best_server()) #Check download speed print(speedTest.download()) #Check upload speed print(speedTest.upload()) # Method 2 import pyspeedtest st = pyspeedtest.SpeedTest() st.ping() st.download() st.upload() 2. Search on Google # pip install google from googlesearch import search query = "Medium.com" for url in search(query): print(url) 3. Make Web Bot # pip install selenium import time from selenium import webdriver from selenium.webdriver.common.keys import Keys bot = webdriver.Chrome("chromedriver.exe") bot.get('[http://www.google.com'](http://www.google.com')) search = bot.find_element_by_name('q') search.send_keys("@codedev101") search.send_keys(Keys.RETURN) time.sleep(5) bot.quit() 4. Fetch Song Lyrics # pip install lyricsgenius import lyricsgenius api_key = "xxxxxxxxxxxxxxxxxxxxx" genius = lyricsgenius.Genius(api_key) artist = genius.search_artist("Pop Smoke", max_songs=5,sort="title") song = artist.song("100k On a Coupe") print(song.lyrics) 5. Get Exif Data of Photos # Get Exif of Photo # Method 1 # pip install pillow import PIL.Image import PIL.ExifTags img = PIL.Image.open("Img.jpg") exif_data = { PIL.ExifTags.TAGS[i]: j for i, j in img._getexif().items() if i in PIL.ExifTags.TAGS } print(exif_data) # Method 2 # pip install ExifRead import exifread filename = open(path_name, 'rb') tags = exifread.process_file(filename) print(tags) 6. OCR Text from Image # pip install pytesseract import pytesseract from PIL import Image pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' t=Image.open("img.png") text = pytesseract.image_to_string(t, config='') print(text) 7. Convert Photo into Cartonize # pip install opencv-python import cv2 img = cv2.imread('img.jpg') grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) grayimg = cv2.medianBlur(grayimg, 5) edges = cv2.Laplacian(grayimg , cv2.CV_8U, ksize=5) r,mask =cv2.threshold(edges,100,255,cv2.THRESH_BINARY_INV) img2 = cv2.bitwise_and(img, img, mask=mask) img2 = cv2.medianBlur(img2, 5) cv2.imwrite("cartooned.jpg", mask) 8. Empty Recycle Bin # pip install winshell import winshell try: winshell.recycle_bin().empty(confirm=False, /show_progress=False, sound=True) print("Recycle bin is emptied Now") except: print("Recycle bin already empty") 9. Python Image Enhancement # pip install pillow from PIL import Image,ImageFilter from PIL import ImageEnhance im = Image.open('img.jpg') # Choose your filter # add Hastag at start if you don't want to any filter below en = ImageEnhance.Color(im) en = ImageEnhance.Contrast(im) en = ImageEnhance.Brightness(im) en = ImageEnhance.Sharpness(im) # result en.enhance(1.5).show("enhanced") 10. Get Window Version # Window Version import wmi data = wmi.WMI() for os_name in data.Win32_OperatingSystem(): print(os_name.Caption) # Microsoft Windows 11 Home @pythonl

🔥 10 Tips And Tricks To Write Better Python Code 10 советов и приемов для написания лучшего кода на Python 1) Iterate c enumerate() вместо range(len()) data = [1, 2, -3, -4] # плохо: for i in range(len(data)): if data[i] < 0: data[i] = 0 # хорошо: data = [1, 2, -3, -4] for idx, num in enumerate(data): if num < 0: data[idx] = 0 2) list comprehension вместо for-loops #плохо: squares = [] for i in range(10): squares.append(i*i) # хорошо: squares = [i*i for i in range(10)] 3) sorted() method data = (3, 5, 1, 10, 9) sorted_data = sorted(data, reverse=True) # [10, 9, 5, 3, 1] data = [{"name": "Max", "age": 6}, {"name": "Lisa", "age": 20}, {"name": "Ben", "age": 9} ] sorted_data = sorted(data, key=lambda x: x["age"]) 4) Хранение данных в Sets my_list = [1,2,3,4,5,6,7,7,7] my_set = set(my_list) # removes duplicates primes = {2,3,5,7,11,13,17,19} 5) Экономьте память с помощью генераторов # list comprehension my_list = [i for i in range(10000)] print(sum(my_list)) # 49995000 # generator comprehension my_gen = (i for i in range(10000)) print(sum(my_gen)) # 49995000 import sys my_list = [i for i in range(10000)] print(sys.getsizeof(my_list), 'bytes') # 87616 bytes my_gen = (i for i in range(10000)) print(sys.getsizeof(my_gen), 'bytes') # 128 bytes 6) Определение значений по умолчанию в словарях с помощью .get() и .setdefault() my_dict = {'item': 'football', 'price': 10.00} count = my_dict['count'] # KeyError! # лучше: count = my_dict.get('count', 0) # optional default value count = my_dict.setdefault('count', 0) print(count) # 0 print(my_dict) # {'item': 'football', 'price': 10.00, 'count': 0} 7) Подсчет хэшируемых объектов с помощью collections.Counter from collections import Counter my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9] counter = Counter(my_list) print(counter) # Counter({9: 6, 10: 3, 5: 2, 2: 1}) print(counter[10]) # 3 from collections import Counter my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9] counter = Counter(my_list) most_common = counter.most_common(2) print(most_common) # [(9, 6), (10, 3)] print(most_common[0]) # (9, 6) print(most_common[0][0]) # 9 8 ) Форматирование строк с помощью f-Strings name = "Alex" my_string = f"Hello {name}" print(my_string) # Hello Alex i = 10 print(f"{i} squared is {i*i}") # 10 squared is 100 9) Конкатенация строк с помощью .join() list_of_strings = ["Hello", "my", "friend"] #плохо: my_string = "" for i in list_of_strings: my_string += i + " " #хорошо list_of_strings = ["Hello", "my", "friend"] my_string = " ".join(list_of_strings) 10) Слияние словарей с синтаксисом двойной звездочки **. d1 = {'name': 'Alex', 'age': 25} d2 = {'name': 'Alex', 'city': 'New York'} merged_dict = {**d1, **d2} @pythonl

🔥 10 Tips And Tricks To Write Better Python Code 10 советов и приемов для написания лучшего кода на Python 1) Iterate c enumerate() вместо range(len()) data = [1, 2, -3, -4] # плохо: for i in range(len(data)): if data[i] < 0: data[i] = 0 # хорошо: data = [1, 2, -3, -4] for idx, num in enumerate(data): if num < 0: data[idx] = 0 2) list comprehension вместо for-loops #плохо: squares = [] for i in range(10): squares.append(i*i) # хорошо: squares = [i*i for i in range(10)] 3) sorted() method data = (3, 5, 1, 10, 9) sorted_data = sorted(data, reverse=True) # [10, 9, 5, 3, 1] data = [{"name": "Max", "age": 6}, {"name": "Lisa", "age": 20}, {"name": "Ben", "age": 9} ] sorted_data = sorted(data, key=lambda x: x["age"]) 4) Хранение данных в Sets my_list = [1,2,3,4,5,6,7,7,7] my_set = set(my_list) # removes duplicates primes = {2,3,5,7,11,13,17,19} 5) Экономьте память с помощью генераторов # list comprehension my_list = [i for i in range(10000)] print(sum(my_list)) # 49995000 # generator comprehension my_gen = (i for i in range(10000)) print(sum(my_gen)) # 49995000 import sys my_list = [i for i in range(10000)] print(sys.getsizeof(my_list), 'bytes') # 87616 bytes my_gen = (i for i in range(10000)) print(sys.getsizeof(my_gen), 'bytes') # 128 bytes 6) Определение значений по умолчанию в словарях с помощью .get() и .setdefault() my_dict = {'item': 'football', 'price': 10.00} count = my_dict['count'] # KeyError! # лучше: count = my_dict.get('count', 0) # optional default value count = my_dict.setdefault('count', 0) print(count) # 0 print(my_dict) # {'item': 'football', 'price': 10.00, 'count': 0} 7) Подсчет хэшируемых объектов с помощью collections.Counter from collections import Counter my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9] counter = Counter(my_list) print(counter) # Counter({9: 6, 10: 3, 5: 2, 2: 1}) print(counter[10]) # 3 from collections import Counter my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9] counter = Counter(my_list) most_common = counter.most_common(2) print(most_common) # [(9, 6), (10, 3)] print(most_common[0]) # (9, 6) print(most_common[0][0]) # 9 8 ) Форматирование строк с помощью f-Strings name = "Alex" my_string = f"Hello {name}" print(my_string) # Hello Alex i = 10 print(f"{i} squared is {i*i}") # 10 squared is 100 9) Конкатенация строк с помощью .join() list_of_strings = ["Hello", "my", "friend"] #плохо: my_string = "" for i in list_of_strings: my_string += i + " " #хорошо list_of_strings = ["Hello", "my", "friend"] my_string = " ".join(list_of_strings) 10) Слияние словарей с синтаксисом двойной звездочки **. d1 = {'name': 'Alex', 'age': 25} d2 = {'name': 'Alex', 'city': 'New York'} merged_dict = {**d1, **d2} @pythonl

⚠️Пройдите тест на углубленные знания в сфере Machine Learning. Professional 🔓 Ответьте на 10 вопросов и проверьте, насколько вы готовы к обучению на продвинутом курсе «Machine Learning. Professional» от OTUS и его партнера — Сбера ⏰ Время прохождения теста ограничено 30 минут 👉 ПРОЙТИ ТЕСТ: https://otus.pw/8y6P/ Курс доступен в рассрочку. 🎁 Пройдете успешно тест, получите доступ к открытым урокам курса. Нативная интеграция. Информация о продукте www.otus.ru

📶 Extract Saved WiFi Passwords in Python Извлечение сохраненных паролей WiFi в Python (Linux OS) import subprocess import os
📶 Extract Saved WiFi Passwords in Python Извлечение сохраненных паролей WiFi в Python (Linux OS) import subprocess import os import re from collections import namedtuple import configparser def get_linux_saved_wifi_passwords(verbose=1): network_connections_path = "/etc/NetworkManager/system-connections/" fields = ["ssid", "auth-alg", "key-mgmt", "psk"] Profile = namedtuple("Profile", [f.replace("-", "_") for f in fields]) profiles = [] for file in os.listdir(network_connections_path): data = { k.replace("-", "_"): None for k in fields } config = configparser.ConfigParser() config.read(os.path.join(network_connections_path, file)) for _, section in config.items(): for k, v in section.items(): if k in fields: data[k.replace("-", "_")] = v profile = Profile(**data) if verbose >= 1: print_linux_profile(profile) profiles.append(profile) return profiles def print_linux_profiles(verbose): """Prints all extracted SSIDs along with Key (PSK) on Linux""" print("SSID AUTH KEY-MGMT PSK") print("-"*50) get_linux_saved_wifi_passwords(verbose) @pythonl

🖥 5 useful Python automation scripts 5 полезных скриптов автоматизации Python 1. Download Youtube videos pip install pytube from pytube import YouTube # Specify the URL of the YouTube video video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # Create a YouTube object yt = YouTube(video_url) # Select the highest resolution stream stream = yt.streams.get_highest_resolution() # Define the output path for the downloaded video output_path = "path/to/output/directory/" # Download the video stream.download(output_path) print("Video downloaded successfully!") 2. Automate WhatsApp messages pip install pywhatkit import pywhatkit # Set the target phone number (with country code) and the message phone_number = "+1234567890" message = "Hello, this is an automated WhatsApp message!" # Schedule the message to be sent at a specific time (24-hour format) hour = 13 minute = 30 # Send the scheduled message pywhatkit.sendwhatmsg(phone_number, message, hour, minute) 3. Google search with Python pip install googlesearch-python from googlesearch import search # Define the query you want to search query = "Python programming" # Specify the number of search results you want to retrieve num_results = 5 # Perform the search and retrieve the results search_results = search(query, num_results=num_results, lang='en') # Print the search results for result in search_results: print(result) 4. Download Instagram posts pip install instaloader import instaloader # Create an instance of Instaloader loader = instaloader.Instaloader() # Define the target Instagram profile target_profile = "instagram" # Download posts from the profile loader.download_profile(target_profile, profile_pic=False, fast_update=True) print("Posts downloaded successfully!") 5. Extract audio from video files pip install moviepy from moviepy.editor import VideoFileClip # Define the path to the video file video_path = "path/to/video/file.mp4" # Create a VideoFileClip object video_clip = VideoFileClip(video_path) # Extract the audio from the video audio_clip = video_clip.audio # Define the output audio file path output_audio_path = "path/to/output/audio/file.mp3" # Write the audio to the output file audio_clip.write_audiofile(output_audio_path) # Close the clips video_clip.close() audio_clip.close() print("Audio extracted successfully!") @pythonl

🔥Хотите стать одним из авторов проектов, которые меняют жизнь людей к лучшему в области автоматизации предприятий, медицины,
🔥Хотите стать одним из авторов проектов, которые меняют жизнь людей к лучшему в области автоматизации предприятий, медицины, робототехники, виртуальной реальности и других сферах, или стать руководителем отдела Computer Vision в вашей компании? Все это возможно после прохождения обучения на курсе “Компьютерное зрение” в OTUS. Сейчас открыт набор в группу. Приходите 29 июня в 20:00 мск на открытый урок «PyTorch 2.0», чтобы познакомиться с преподавателем и программой курса, оценить все перспективы, которые откроются перед вами. На занятии мы также обсудим, что нового принес фреймворк PyTorch 2.0 в сферу компьютерного зрения и глубокого обучения. 📌Вы узнаете: - Как начать использовать PyTorch для обучения своих нейронных сетей - Что нового в PyTorch 2.0 и чем он отличается от 1.x - Как ускорить и оптимизировать свою нейросеть при помощи одной строчки кода - Как перейти с PyTorch 1.x на 2.0 - Как ускорить трансформеры HuggingFace при помощи PyTorch Transformer API 👉🏻Для участия отправьте заявку https://otus.pw/XgxP/ Кому подходит этот урок: - Начинающим и опытным специалистам в области компьютерного зрения и глубокого обучения - Дата сайентистам, которые хотят ускорить инференс своих моделей - Опытным специалистам, которые еще не перешли на PyTorch 2.0 - Тем, кто хочет познакомиться с фреймворков PyTorch и начать обучать свои нейросети Нативная интеграция подробная информация о продукте www.otus.ru

A Minimal Example of Machine Learning (with scikit-learn) Минимальный пример кода машинного обучения (с помощью scikit-learn)
A Minimal Example of Machine Learning (with scikit-learn) Минимальный пример кода машинного обучения (с помощью scikit-learn) import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier data = [{'humidity': 80, 'wind': 20, 'temp': 15, 'clouds': 90, 'raining?': 'yes'}, {'humidity': 40, 'wind': 5, 'temp': 25, 'clouds': 15, 'raining?': 'no'}, {'humidity': 20, 'wind': 30, 'temp': 35, 'clouds': 50, 'raining?': 'no'}, {'humidity': 90, 'wind': 3, 'temp': 18, 'clouds': 100, 'raining?': 'yes'}, {'humidity': 70, 'wind': 13, 'temp': 22, 'clouds': 75, 'raining?': 'no'}, {'humidity': 85, 'wind': 10, 'temp': 17, 'clouds': 90, 'raining?': 'yes'}, {'humidity': 90, 'wind': 20, 'temp': 20, 'clouds': 80, 'raining?': 'yes'}, {'humidity': 60, 'wind': 5, 'temp': 23, 'clouds': 30, 'raining?': 'no'}, {'humidity': 95, 'wind': 25, 'temp': 13, 'clouds': 100, 'raining?': 'yes'}, {'humidity': 70, 'wind': 2, 'temp': 30, 'clouds': 100, 'raining?': 'no'}, ] df = pd.DataFrame(data, columns=['humidity', 'wind', 'temp', 'clouds', 'raining?']) print(df) X, y = df.to_numpy()[:8, :4], df.to_numpy()[:8, 4] model = RandomForestClassifier() model.fit(X, y) model.predict([[95, 25, 13, 100],[70, 2, 30, 100]]).reshape(1, -1) @pythonl