Recetas Python¶
Genérico¶
Genera una secuencia de números de Fibonacci¶
#!/usr/bin/python3
# Secuencia de Fibonacci
#
# Genera Iterativamente
from typing import Generator
def fib(n: int) -> Generator[int, None, None]:
yield 0 # caso especial
if n > 0: yield 1 # caso especial
ultimo: int = 0 # inicialmente fib(0)
nuevo: int = 1 # inicialmente fib(1)
for _ in range(1, n):
ultimo, nuevo = nuevo, ultimo + nuevo
yield nuevo # paso principal del generador
if __name__ == "__main__":
for i in fib(50):
print(i)
Trasponer una matriz¶
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data_transpose)
devuelve ((0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11))
Ficheros¶
Volcado en base de datos desde una excel¶
#! python3
# Genera los inserts necesarios para insertar/actualizar las especialidades dadas
# a partir de los datos pasados en una excel.
# Datos de la excel
# -----------------
# - En cada fila va una especialidad
# - Existe una fila de encabezado
# - Los campos son los siguientes:
# A. Código especialidad
# B. Denominación
# C. Familia
# D. Área
# E. Fecha alta
# F. Origen (siempre SEPE)
# G. Importe Módulo A (siempre 6)
# H. Importe Módulo prácticas (siempre 0)
# I. Número de horas totales
# H. Número de alumnos (siempre 15 ?)
# K. Código módulo de prácticas
# L. Nivel formativo (siempre 0)
# M. Normalizada (siempre SI)
# N. Solicitud de Cursos (siempre SI)
# O. Solicitud de Homologaciones (siempre SI)
# P. Modular (siempre NO)
# 1.Declaración de constantes
FICH_EXCEL = 'ESPECIALIDADES_PO.xlsx'
FICH_SQL = 'inserts.sql'
SQLOUTPUT = open(FICH_SQL, 'w')
# 2.Se carga la excel en memoria
import openpyxl
wb = openpyxl.load_workbook(FICH_EXCEL)
ws = wb.get_active_sheet() #la hoja principal es la primera
# 3.Se recorre la excel por filas
for r in range(2, ws.max_row+1):
# 3.1. Se definen los datos
espCod = str(ws['A' + str(r)].value).strip()
espFecAlt = str(ws['E' + str(r)].value).strip()
famCod = espCod[:3]
areCod = espCod[:4]
espDes = str(ws['B' + str(r)].value).strip()
espHor = str(ws['I' + str(r)].value).strip()
# 3.2 Se construye la sql correspondiente a VAL_ESP_FOR
sql = "INSERT INTO VAL_ESP_FOR ( \n"
sql += "\t ESP_COD, ESP_FEC_ALT,\n"
sql += "\t FAM_COD, ARE_COD, NIV_FOR, ESP_DES, ESP_DES_NOR,\n"
sql += "\t ESP_INE, ESP_NOR, ESP_CUR, ESP_HOM, ESP_DES_ABR, ESP_DES_ABR_NOR,\n"
sql += "\t ESP_MOD, EFV_FEC_INI, \n"
sql += "\t EFV_ESP_ALU, EFV_ESP_HOR, EFV_MDA_EUR, EFV_MDB_EUR)\n"
sql += "VALUES (\n"
sql += "\t '" + espCod +"', to_date('" + espFecAlt +"', 'DD/MM/YYYY'),\n"
sql += "\t '" + famCod +"', '" + areCod +"', '0', '" + espDes[:200] +"','" + espDes[:200] + "',\n"
sql += "\t 'E', 'S', 'S', 'S', '" + espDes[:30] +"','" + espDes[:30] + "',\n"
sql += "\t 'N', to_date('" + espFecAlt +"', 'DD/MM/YYYY'),\n"
sql += "\t 15, '" + espHor + "', 6, 0\n"
sql += "\t);\n"
# 3.3 Se construye la sql correspondiente a VAL_ESP_FOR_VIG
sql += "INSERT INTO VAL_ESP_FOR_VIG ( \n"
sql += "\t ESP_COD, EFV_FEC_INI, \n"
sql += "\t EFV_ESP_ALU, EFV_ESP_HOR, EFV_MDA_EUR, EFV_MDB_EUR)\n"
sql += "VALUES (\n"
sql += "\t '" + espCod +"', to_date('" + espFecAlt +"', 'DD/MM/YYYY'),\n"
sql += "\t 15, '" + espHor + "', 6, 0\n"
sql += "\t);\n"
# 3.4 Se graba en el fichero
SQLOUTPUT.write(sql)
# 4.Se cierran los ficheros
wb.close()
SQLOUTPUT.close()
Markdown Itemize¶
#! python
# bulletPointAdder.py - Añade markdown bullet points al inicio
# de cada línea de texto en el portapapeles
import pyperclip
text = pyperclip.paste()
# Separar líneas y añadir asteriscos
lines = text.split('\n')
for i in range(len(lines)):
lines[i] = '* ' + lines[i]
text = '\n'.join(lines)
pyperclip.copy(text)
Lista el árbol de subdirectorios y ficheros del directorio dado¶
#! python
# listaFicheros.py - Lista el árbol de subdirectorios y ficheros del directorio dado
# Uso: py.exe listaFicheros.py <directorio>
import os, sys
if len(sys.argv) == 1 :
dirTrabajo = os.curdir
else :
dirTrabajo = sys.argv[1]
print (dirTrabajo)
for directorio, subdirectorios, ficheros in os.walk(dirTrabajo):
print('El directorio actual es ' + directorio)
for subdirectorio in subdirectorios:
print('SUBDIRECTORIO DE ' + directorio + ': ' + subdirectorio)
for fichero in ficheros:
print('FICHERO EN ' + directorio + ': ' + fichero)
print('')
Renombra ficheros con fecha en formato americano a formato europeo¶
#! python
# renombraFechas.py - Renombra ficheros con fechas americanas en el nombre
# a fechas europeas
# Nota: sólo tiene en cuenta años desde el 1900
import shutil, os, re
# Crea una expresión regular para ficheros con fecha en formato americano
patronFecha = re.compile(r"""^(.*?) # cualquier texto antes de la fecha
((0|1)?\d)- # uno o dos dígitos para el mes
((0|1|2|3)?\d)- # uno o dos dígitos para el día
((19|20)\d\d) # cuatro dígitos para el año
(.*?)$ # cualquier texto después de la fecha
""", re.VERBOSE)
# Recorre todos los ficheros del directorio de trabajo
for amerFichero in os.listdir('.') :
mo = patronFecha.search(amerFichero)
# Omite los ficheros sin fecha en formato americano
if mo == None :
continue
# Obtiene las diferentes partes del nombre del ficheros
antesFecha = mo.group(1)
mes = mo.group(2)
dia = mo.group(4)
anno = mo.group(6)
trasFecha = mo.group(8)
# Construye el nombre del fichero con la fecha con formato europeo
euroFichero = antesFecha + dia + '-' + mes + '-' + anno + trasFecha
# Obtiene las rutas absolutas de los ficheros
absDirTrabajo = os.path.abspath('.')
amerFichero = os.path.join(absDirTrabajo, amerFichero)
euroFichero = os.path.join(absDirTrabajo, euroFichero)
# Renombra el fichero
print('Renombrando "%s" a "%s"...' % (amerFichero, euroFichero))
shutil.move(amerFichero, euroFichero)
Convert any .pdf file 📚 into an audio 🔈 book with Python¶
A while ago I was messing around with google’s Text to Speech python library.
This library basically reads out any piece of text and converts it to .mp3
file. Then I started thinking of making something useful out of it.
My installed, saved, and unread pdf books 😕¶
I like reading books. I really do. I think language and ideas sharing is fascinating. I have a directory at which I store pdf books that I plan on reading but I never do. So I thought hey, why dont I make them audio books and listen to them while I do something else 😄!
So I started planning how the script should look like.
- Allow user to pick a
.pdf file
- Convert the file into one string
- Output
.mp3
file.
Without further needless words, lets get to it.
Allow user to pick a .pdf file¶
Python can read files easily. I just need to use the method open("filelocation", "rb")
to open the file in reading mode. I dont want to be copying and pasting files to the directory of the code everytime I want to use the code though. So to make it easier we will use tkinter library
to open up an interface that lets us choose the file.
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
Great. Now we have the file location stored in a filelocation
variable.
Allow user to pick a .pdf file ✔️
Convert the file into one string¶
As I said before, to open a file in Python we just need to use the open()
method. But we also want to convert the pdf file into regular pieces of text. So we might as well do it now.
To do that we will use a library called pdftotext
.
Lets install it:
sudo pip install pdftotext
Then:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdftotext
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
with open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it f
pdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variable
Great. Now we have the file stored in the variable pdf
.
if you print this variable, you will get an array of strings. Each string is a line in the file. to get them all into one .mp3
file, we will have to make sure they are all stored as one string. So lets loop through this array and add them all to one string.
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdftotext
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
with open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it f
pdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variable
string_of_text = ''
for text in pdf:
string_of_text += text
Sweet 😄. Now we have it all as one piece of string.
Convert the file into one string ✔️
Output .mp3 file 🔈¶
Now we are ready to use the gTTS
(google Text To Speech) library. all we need to do is pass the string we made, store the output in a variable, then use the save()
method to output the file to the computer.
Lets install it:
sudo pip install gtts
Then:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdftotext
from gtts import gTTS
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI
with open(filelocation, "rb") as f: # open the file in reading (rb) mode and call it f
pdf = pdftotext.PDF(f) # store a text version of the pdf file f in pdf variable
string_of_text = ''
for text in pdf:
string_of_text += text
final_file = gTTS(text=string_of_text, lang='en') # store file in variable
final_file.save("Generated Speech.mp3") # save file to computer
As simple as that! we are done 🎇
Servicios¶
Predicción meteorológica del lugar pasado como argumento¶
#! python3
# tiempo.py - Imprime la predicción meteorológica para un lugar por línea de comandos
import json, requests, sys
# Localización (por defecto, Valladolid)
if len(sys.argv) < 2:
location = 'Valladolid,ES'
else:
location = ' '.join(sys.argv[1:])
# Se descargan los datos (en formato JSON) de OpenWeatherMap.org
# para ello es necesario obtener la clave de API que ofrecen al suscribirse
# Tiempo actual
url ='http://api.openweathermap.org/data/2.5/weather?q=%s&appid=42dc2083f19202a48773818ad7bfef70&units=metric&lang=es' % (location)
response = requests.get(url)
response.raise_for_status()
# Se guardan los datos JSON en una variable Python
w = json.loads(response.text)
# Se imprime por pantalla
print('Tiempo actual en', w['name'], '(', w['sys']['country'], ')')
print('\t Temperatura:', w['main']['temp'], 'grados')
print('\t Viento:', w['wind']['speed'], 'm/s')
print('\t Humedad:', w['main']['humidity'], '%')
print('\t Clima:', w['weather'][0]['description'])
print()
# Predicción
url ='http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=3&appid=42dc2083f19202a48773818ad7bfef70&units=metric&lang=es' % (location)
response = requests.get(url)
response.raise_for_status()
# Se guardan los datos JSON en una variable Python
weatherData = json.loads(response.text)
# Se imprime por pantalla
w = weatherData['list']
print('Mañana:')
print('\t Temperatura entre', w[1]['temp']['min'], 'y', w[1]['temp']['max'], 'grados')
print('\t Viento:', w[1]['speed'], 'm/s')
print('\t Humedad:', w[1]['humidity'], '%')
print('\t Clima:', w[1]['weather'][0]['description'])
print()
print('Pasado mañana:')
print('\t Temperatura entre', w[2]['temp']['min'], 'y', w[2]['temp']['max'], 'grados')
print('\t Viento:', w[2]['speed'], 'm/s')
print('\t Humedad:', w[2]['humidity'], '%')
print('\t Clima:', w[2]['weather'][0]['description'])
Generar contraseña aleatoria¶
#! python3
# pass.py - Genera contraseñas aleatorias
# --- Como parametro se le puede pasar el número de contraseñas (por defecto 1)
# --- Las contraseñas con numéricas de 6 dígitos
# --- Utiliza la web https://www.random.org
# --- El resultado lo muestra por pantalla y lo copia al portapapeles
import requests, sys, urllib, pyperclip
if len(sys.argv) > 1:
# Toma el número de contraseñas por línea de comandos.
num = ' '.join(sys.argv[1:])
else:
# Toma por defecto una contraseña
num = '1'
# Proxy
http_proxy = "http://localhost:5865"
proxyDict = {
"http" : http_proxy,
"https" : http_proxy
}
r = requests.get(
'https://www.random.org/strings/?num=' + num + '&len=6&digits=on&unique=on&format=plain&rnd=new',
proxies=proxyDict
)
print (r.text)
pyperclip.copy(r.text)
print ('Copiado al portapapeles')
Traductor¶
Abre un navegador donde traduce la frase pasada como parámetro con Google Translate al español
#! python3
# translate.py - Launches browser with the translation of a sentence
# from the command line or clipboard. The target language is a constant
import webbrowser, sys, pyperclip
TARGET = 'es' #español
if len(sys.argv) > 1:
# Get address from command line.
sentence = ' '.join(sys.argv[1:])
else:
# Get address from clipboard.
sentence = pyperclip.paste()
webbrowser.open('https://translate.google.es/#auto/' + TARGET + '/' + sentence)
Mapa¶
Abre un navegador con google maps en el lugar pasado como argumento
#! python3
# mapIt.py - Launches a map in the browser using an address from the
# command line or clipboard.
# Automate the Boring Stuff with Python, Albert Sweigart
import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
# Get address from command line.
address = ' '.join(sys.argv[1:])
else:
# Get address from clipboard.
address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/place/' + address)
Abre un navegador con google maps y muestra cómo ir al lugar indicado
#! python3
# goTo.py - Launches a map in the browser with the path to one target
# from the command line or clipboard.
# The origin is one constant
import webbrowser, sys, pyperclip
ORIGIN = 'Valladolid, España'
if len(sys.argv) > 1:
# Get address from command line.
address = ' '.join(sys.argv[1:])
else:
# Get address from clipboard.
address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/dir/' + ORIGIN + '/' + address)
Servidor web¶
Para lanzar un servidor web con python es suficiente con ejecutar, desde la ruta que queramos:
python -m http.server
y ya tendremos nuestro servidor web accesible en el puerto 8000.