Python/ django
58.9K subscribers
2.08K photos
61 videos
47 files
2.79K links
по всем вопросам @haarrp

@itchannels_telegram - 🔥 все ит-каналы

@ai_machinelearning_big_data -ML

@ArtificialIntelligencedl -AI

@datascienceiot - 📚

@pythonlbooks

РКН: clck.ru/3FmxmM
加入频道
📌 Boost Your Data Analysis Efficiency: Essential NumPy and Pandas Shortcuts You Should Know

Повышение эффективности анализа данных: Топ примеров кода NumPy и Pandas, которые помогут вам в работе.

1. NumPy (изображение 1.)
2. Pandas Series and DataFrame (изображение 2.)
3. Pandas Functions and Maps (изображение 3.)
4. Pandas Grouping and Sorting (изображение 4.)
5. Pandas Data Types and Missing Values (изображение 5.)
6. Pandas Data Visualization (изображение 6.)

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 🔍 Web Scraping with Python, Selenium, and Tor: A Powerful Combination

Веб-скрепинг с помощью Python, Selenium и Tor: Мощная комбинация для парсинга.

import subprocess
import time
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.firefox.options import Options

# Define the command to start Tor. This will depend on your operating system and configuration.
command = '<<path_to_tor>>/tor.exe'

# Start the Tor process
tor_process = subprocess.Popen(command, stdout=subprocess.PIPE)

# Wait for Tor to start up
time.sleep(5)

# Sets up proxy settings for the Firefox browser driver
proxy_settings = Proxy({
'proxyType': ProxyType.MANUAL,
'socksProxy': '127.0.0.1:9050',
'socksVersion': 5
})

options = Options()
options.proxy = proxy_settings

driver = webdriver.Firefox(options=options)
driver.get('https://check.torproject.org') # Check if we are using Tor

# When you're done, don't forget to stop the Tor process
tor_process.terminate()

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
📹 Simple Screen Recording with Python.

Делаем запись экрана с помощью Python.

📌Code

@pythonl
Solving Captcha with Puppeteer and Python

Решение кпчи с помощью Puppeteer и Python.

import asyncio
from pyppeteer import launch
from capsolver_api import HCaptchaTask


async def main():
url = 'https://accounts.hcaptcha.com/demo'
browser = await launch(headless=False)
page = await browser.newPage()
await page.goto(url)
element = await page.querySelector('#hcaptcha-demo')
website_key = await page.evaluate('(element) => element.getAttribute("data-sitekey")', element)

capsolver = HCaptchaTask('your_capsolver_api_key')

task_id = capsolver.create_task(task_type='HCaptchaTaskProxyLess',
website_url=url,
website_key=website_key
)

captcha_key = capsolver.get_solution(task_id)

await page.waitForSelector('iframe')
await page.type('textarea[name="h-captcha-response"]', captcha_key)
await page.click('input[type="submit"]')
await page.waitFor(2000)
await page.screenshot({'path': 'solve.png'}) # screenshot of the solved captcha

asyncio.get_event_loop().run_until_complete(main())

@pythonl
🔐 Decrypt Browser Passwords

A simple program to decrypt chrome password saved on your machine.

Простая программа для расшифровки пароля chrome, сохраненного на вашем компьютере на Python.


Github

@pythonl
This media is not supported in your browser
VIEW IN TELEGRAM
🦅 Trafilatura

Python & command-line tool to gather text on the Web: web crawling/scraping, extraction of text, metadata, comments

Это Python бибилиотека и инструмент командной строки для парсинга и сбора текста с сайтов.

Инструмент способен к сбору основного текста, метаданных и комментариев
.

Github
Tutorials
Python Notebook

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Testing FastAPI with async database session

Тестирование FastAPI с асинхронной сессией базы данных.

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Unlocking the Power of PyScript: A Guide to Running Python Code in Your HTML

Руководство по выполнению кода Python в HTML.

Веб-приложение, выполняющее анализ настроений в тексте, предоставленном пользователем, с помощью предварительно обученной модели машинного обучения на языке Python.

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
🎤🔤 Embrace the Power of Speech-to-Text in Python!

Представляет собой пошаговый пример кода на языке Python, использующий библиотеку SpeechRecognition для преобразования речи в текст.

pip install SpeechRecognition

import speech_recognition as sr

recognizer = sr.Recognizer()


with sr.Microphone() as source:
print("Say something...")
recognizer.adjust_for_ambient_noise(source) # Optional: Adjust for background noise
audio = recognizer.listen(source)


audio_file = "path/to/your/audio_file.wav" # Replace with the path to your audio file
with sr.AudioFile(audio_file) as source:
audio = recognizer.listen(source)


try:
print("Converting speech to text...")
text = recognizer.recognize_google(audio)
print("You said:", text)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand the audio.")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))


@pythonl
🔢 How To Code a Simple Number Guessing Game in Python

Пишем игру для угадывания чисел на Python.

# main.py
import random

# define range and max_attempts
lower_bound = 1
upper_bound = 1000
max_attempts = 10

# generate the secret number
secret_number = random.randint(lower_bound, upper_bound)

# Get the user's guess
def get_guess():
while True:
try:
guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))
if lower_bound <= guess <= upper_bound:
return guess
else:
print("Invalid input. Please enter a number within the specified range.")
except ValueError:
print("Invalid input. Please enter a valid number.")

# Validate guess
def check_guess(guess, secret_number):
if guess == secret_number:
return "Correct"
elif guess < secret_number:
return "Too low"
else:
return "Too high"

# track the number of attempts, detect if the game is over
def play_game():
attempts = 0
won = False

while attempts < max_attempts:
attempts += 1
guess = get_guess()
result = check_guess(guess, secret_number)

if result == "Correct":
print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
won = True
break
else:
print(f"{result}. Try again!")

if not won:
print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")

if __name__ == "__main__":
print("Welcome to the Number Guessing Game!")
play_game()


@pythonl