aprendepython | Technologies

Telegram-канал aprendepython - Aprende Python

4758

Recursos de aprendizaje para #Python, #Django y Flask @TodoPythonCanal

Subscribe to a channel

Aprende Python

Buenas.

Ya estamos en Agosto, como comente a lo largo del mes este canal estará en modo vacaciones hasta Septiembre, eso significa que publicare contenido de una forma mas relajada, una vez por semana, espero que moleste pero el mes de Agosto lo necesito para recuperar fuerzas.

Un saludo.

Читать полностью…

Aprende Python

Introduction to MicroPython
https://docs.arduino.cc/micropython-course/course/introduction-python

Читать полностью…

Aprende Python

Hasta finales de Julio me tomare un descanso, no voy a publicar contenido, en Agosto volveré aunque de un forma mas relajada, lo que yo llamo estará el canal en modo vacaciones, publicaré contenido pero con menos periodicidad.
En Septiembre volveré con la periodicidad habitual.

Que tengas buenas vacaciones y buen descanso.

Un saludo.

Читать полностью…

Aprende Python

🚀 Python code that can send WhatsApp messages, send emails, and send SMS messages to a number.

Python-скрипты для отправки сообщений WhatsApp, электронных письмем и SMS-сообщений.

@pythonl

Читать полностью…

Aprende Python

Python se utiliza en múltiples ámbitos sitios y uno de ellos es el campo de la Estadística, en el siguiente artículo explica como utilizar Python para modelos estadísticos, que herramienta hay disponible y ejemplos de uso.

https://bit.ly/3OcVIVx
#estadistica

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Читать полностью…

Aprende Python

🚀 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

Читать полностью…

Aprende Python

🕸 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

Читать полностью…

Aprende Python

El siguiente artículo no es de desarrollo propiamente dicho, pero me ha parecido muy interesante, y desconocido para mi, lo que explica.

Dentro de la librería estandar de Python tenemos un conjunto de módulo que se pueden utilizar como herramienta para terminal con python -m nombre_modulo.

En el siguiente artículo muestra como ha descubierto todas esas herramientas y explica alguna de ellas.

https://bit.ly/3pvLKoH
#CLI

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Читать полностью…

Aprende Python

🖥 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

Читать полностью…

Aprende Python

Si quieres hacer una pequeña aportación para mejorar mis proyectos lo puedes hacer por los métodos que he descrito en el mensaje anterior, o por Telegram, os lo agradecería mucho.

Читать полностью…

Aprende Python

En el siguiente artículo es una reflexión sobre algo que los programadores se enfrentan a diario que es la depuración de ćodigo. El autor explica porque y como depurar código de forma eficiente.

https://bit.ly/46vDGF6
#debug

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Audio Curso Aprendiendo Telegram https://mumbler.io/aprendiendo-telegram

Читать полностью…

Aprende Python

Lo anterior esta en ruso, recordar que Telegram permite traducir texto y del Ruso a Español esta soportado.

Читать полностью…

Aprende Python

También me puedes apoyar por Telegram, estaré muy agradecido y motivara para seguir en estos días tan caluroso.

Читать полностью…

Aprende Python

¿Sabes lo que es LoB "the location of Behaviour"? En caso negativo ,puedes aprenderlo en el siguiente artículo donde lo aplica a las URLs y vistas de Django.

https://bit.ly/3pkxTS3
#django

Читать полностью…

Aprende Python

En este caso es un recurso algo diferente, porque no es un enlace a una web, si no un un enlace compartido de una carpeta Data Science.

Para quien no sepa que es esa funcionalidad en Telegram, el siguiente enlace es de un carpeta con grupos y canales de ese ámbito. cuando pulsas en el enlace, tendrás un listado que podrás decidir donde entras y donde no, cuando confirmas en tu cliente de Telegram aparecerá esa carpeta con los canales y grupo que te has unido.

Asi que aquí tienes una carpeta de Data Science.

/channel/addlist/8_rRW2scgfRhOTc0

Читать полностью…

Aprende Python

Anuncio el sistema de invitados del canal de Telegram Un Día Una Aplicación.

El sistema es simple, si te suscribes al canal podrás invitar a un usuario, hasta máximo 2 meses, en función del tiempo que pague la suscripción.

Si pagas un mes el invitado obtiene un mes, si pagas dos meses, el invitado obtiene dos meses gratis de acceso al canal, finalizado ese plazo de dos meses el invitado no tendrás más meses gratis.

Sólo debe proporcionarme la persona que paga la suscripción el alias de Telegram del invitado .

Este sistema tiene las siguiente normas.

▪️Sólo se puede ser invitado una vez al año, haya tenido un mes o dos meses gratis.

▪️ Sólo puede existir un invitado por suscriptor , aunque ese suscriptor sigue puede tener varios invitados consecutivos. Por ejemplo, el suscriptor paga dos meses y tiene un invitado, los siguientes dos meses tiene otro invitado. Como máximo el suscriptor solo podrá tener 6 meses con invitados.

▪️El sistema de invitados es opcional, el suscriptor decide cuando y si quiere invitar, siempre cumpliendo las normas anteriores.

▪️Es obligatorio que el invitado tenga alias de Telegram . El nombre que empieza con @


Cualquier duda me lo preguntáis en mi cuenta @JoseAJimenez.

Para el pago de la suscripción al canal, 3€ al mes

/channel/+fQhsFUJto6lkYjA0

Читать полностью…

Aprende Python

Con este periodo de vacacional recordad que tenéis varias forma para realizar pequeñas aportaciones, os lo agradeceré mucho y siempre es una forma de valorar mi tiempo. Ademas es un factor motivante muy grande.

Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

También podeis probar el servicio de IGraal que devuelven parte del importe de las compras realizas un muchas tiendas.
iGraal https://es.igraal.com/padrinazgo?padrino=AG_6335a460d3e92

Читать полностью…

Aprende Python

Como limpiar código no usado utilizando la herramienta Vulture, que fue la primera herramienta que publique en mi otro canal de Python @UnPythonAlDia

https://bit.ly/3rqo0D1
#optimizacion

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Читать полностью…

Aprende Python

Artículo donde explican como aumentar la velocidad de Python usando Rust.

https://bit.ly/3riCxQS
#optimizacion

Читать полностью…

Aprende Python

YA TENEMOS  PRIME DAY !!!
El 12 y 13 de Julio
muchas ofertas en Amazon ,solo para clientes de Amazon Prime.

Si no eres cliente de ese servicio  no te preocupes, puedes apuntarte utilizar el periodo de PRUEBA con los siguientes .

Amazon Prime (1 mes de prueba) https://amzn.to/3xnYc9a

Si eres estudiante, puede utilizar Amazon Prime Student((90 días de prueba) https://amzn.to/3nQZvKR

Si ya eres cliente de Amazon Prime puedes utilizar mi enlace de referido 

Utiliza mi link, me podrás apoyar sin gastar dinero y aprovechar todas las ofertas del Primer Day
https://amzn.to/3s0zEk2

También puede apuntarte al periodo de PRUEBA del servicios de audiolibro de Amazon que se llama Audible, que ahora han subido la comisión que recibo. Si quieres probarlo y ayudarme .

https://www.amazon.es/hz/audible/mlp/mdp/discovery?actionCode=AMSTM1450129210001&tag=rooteando0e-21

Estas aportaciones me permitirán sostener mis proyecto actuales y futuros, mejorar mi equipo, para un nuevo micro y brazo por ejemplo.

Muchas gracias por el apoyo.

Читать полностью…

Aprende Python

Si quieres apoyarme y realizar una pequeña aportación económica, será una buena motivación y una forma de valorar el tiempo que le dedico a los canales de Python.

Podeís hacerlo por los métodos publicados en los mensajes(Kofi, PayPal, Buy me Coffe o Amazon Afiliados), también utilizando Telegram para donar.

Читать полностью…

Aprende Python

Artículo que introduce a los conceptos de Manager y QuerySet en Django con un ejemplo donde muestra sus diferencias, virtudes y defectos.

https://bit.ly/3D47Dyg
#django #bd

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Читать полностью…

Aprende Python

El siguiente enlace es un repositorio de GitHub con una colección de scripts para automatizar tareas comunes, te puedes encontrar desde tareas para backup, desarrollo web(testing, despliegue o scraping), Data Science, seguridad y otras.

https://github.com/Chamepp/Daily.py
#automatizacion

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Читать полностью…

Aprende Python

📽 Python for DataScience | Short Courses
آموزش ویدیویی مقدمات پایتون برای علوم داده.

🔗 https://youtu.be/yGN28LY5VuA

#Python #DataScience
#Courses

@ai_python

Читать полностью…

Aprende Python

El siguiente enlace tenemos un artículo donde explica como escribir código de calidad y como automatizar ese proceso.

https://bit.ly/3r7P4qj
#desarrollo #calidad

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Audio Curso Aprendiendo Telegram https://mumbler.io/aprendiendo-telegram

Читать полностью…

Aprende Python

Como configurar un sistema de cache utilizando Redis en Django, en el siguiente artículo te explica como hacerlo y con un ejemplo práctico.

https://bit.ly/3CTfUoN
#django #cache

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Audio Curso Aprendiendo Telegram https://mumbler.io/aprendiendo-telegram

Читать полностью…

Aprende Python

🔥 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

Читать полностью…

Aprende Python

Como diseñar una API "pythonic", en el siguiente artículo explica las cualidades que debe tener una buena API.

https://bit.ly/3pnYWvJ
#API

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Audio Curso Aprendiendo Telegram https://mumbler.io/aprendiendo-telegram

Читать полностью…

Aprende Python

El siguiente artículo es como dice "café para muy cafeteros" porque trata de como hacer con Python un hypervisor de KVM.

https://www.devever.net/~hl/kvm
#virtualizacion

Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Ko-fi https://ko-fi.com/josjimenez
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Audio Curso Aprendiendo Telegram https://mumbler.io/aprendiendo-telegram

Читать полностью…

Aprende Python

Cuando estas aprendiendo de nuevo ámbito y de los problemas es encontrar buenos ejemplos y datos para practicar. Pues si en un caso estas empezando en el mundo de Data Science, en el enlace siguientes encontraras 32 datasets(conjuntos de datos) de diversos ámbitos y niveles de dificultad, con una pregunta tipo desafio, para que practiques y mejores tus habilidades.

https://bit.ly/430wGwX
#datos


Apoyame, lo agradecería mucho y es un factor motivante muy importante.
Buy me Coffe https://buymeacoffee.com/jajt
PayPal https://paypal.me/JoseAJimenez
Amazon afiliados https://amzn.to/3s0zEk2

Audio Curso Aprendiendo Telegram https://mumbler.io/aprendiendo-telegram

Читать полностью…
Subscribe to a channel