Librerie standard e avanzate
Python offre una vasta gamma di librerie standard avanzate che ti permettono di svolgere operazioni complesse in modo semplice ed efficiente.
datetime
: Gestione di date e ore
-
Cosa fa?
- Fornisce classi per manipolare date, ore e intervalli di tempo.
-
Classi principali:
datetime
: combina data e ora.date
: gestisce solo la data.time
: gestisce solo l'ora.timedelta
: rappresenta una durata (differenza tra due date o ore).
-
Esempi:
from datetime import datetime, date, timedelta # Data e ora corrente ora_corrente = datetime.now() print(ora_corrente) # Output: 2023-10-25 12:34:56.789012 # Creazione di una data specifica data = date(2023, 10, 25) print(data) # Output: 2023-10-25 # Differenza tra due date differenza = timedelta(days=5) nuova_data = data + differenza print(nuova_data) # Output: 2023-10-30
collections
: Tipi di dati avanzati
-
Cosa fa?
- Fornisce strutture dati specializzate oltre a quelle built-in come liste, tuple e dizionari.
-
Strutture principali:
-
defaultdict
: un dizionario con valori predefiniti.from collections import defaultdict diz = defaultdict(int) # Valori predefiniti sono 0 diz["chiave"] += 1 print(diz["chiave"]) # Output: 1 -
Counter
: conta le occorrenze di elementi.from collections import Counter lista = ["a", "b", "a", "c", "b", "a"] conteggio = Counter(lista) print(conteggio) # Output: Counter({'a': 3, 'b': 2, 'c': 1}) -
deque
: una coda a doppia estremità.from collections import deque coda = deque([1, 2, 3]) coda.append(4) # Aggiunge in coda coda.appendleft(0) # Aggiunge in testa print(coda) # Output: deque([0, 1, 2, 3, 4])
-
itertools
: Operazioni avanzate su iterabili
-
Cosa fa?
- Fornisce funzioni per creare e manipolare iteratori.
-
Funzioni principali:
-
permutations
: genera tutte le permutazioni di un iterabile.from itertools import permutations perm = permutations([1, 2, 3]) print(list(perm)) # Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), ...] -
combinations
: genera tutte le combinazioni di un iterabile.from itertools import combinations comb = combinations([1, 2, 3], 2) print(list(comb)) # Output: [(1, 2), (1, 3), (2, 3)] -
cycle
: cicla infinitamente su un iterabile.from itertools import cycle ciclico = cycle([1, 2, 3]) for _ in range(5): print(next(ciclico)) # Output: 1, 2, 3, 1, 2
-
re
: Espressioni regolari
-
Cosa fa?
- Permette di cercare, estrarre e manipolare testo usando pattern.
-
Funzioni principali:
-
search
: cerca un pattern in una stringa.import re testo = "Ciao, il mio numero è 123-456-7890" match = re.search(r"\d{3}-\d{3}-\d{4}", testo) if match: print("Trovato:", match.group()) # Output: Trovato: 123-456-7890 -
findall
: trova tutte le occorrenze di un pattern.numeri = re.findall(r"\d+", testo) print(numeri) # Output: ['123', '456', '7890'] -
sub
: sostituisce un pattern con una stringa.nuovo_testo = re.sub(r"\d{3}-\d{3}-\d{4}", "XXX-XXX-XXXX", testo) print(nuovo_testo) # Output: Ciao, il mio numero è XXX-XXX-XXXX
-
os
e shutil
: Gestione di file e directory
-
os
:- Interagisce con il sistema operativo (es. gestione di file, directory, variabili d'ambiente).
- Esempi:import os # Creare una directory os.mkdir("nuova_directory") # Listare i file in una directory print(os.listdir(".")) # Ottenere il percorso corrente print(os.getcwd())
-
shutil
:- Fornisce operazioni di alto livello per la gestione di file e directory (es. copia, spostamento).
- Esempi:import shutil # Copiare un file shutil.copy("file.txt", "copia_file.txt") # Spostare un file shutil.move("file.txt", "nuova_directory/file.txt")
subprocess
: Esecuzione di comandi di sistema
-
Cosa fa?
- Permette di eseguire comandi di sistema direttamente da Python.
-
Funzioni principali:
-
run
: esegue un comando e cattura l'output.import subprocess risultato = subprocess.run(["ls", "-l"], capture_output=True, text=True) print(risultato.stdout) # Stampa l'output del comando -
Popen
: offre un controllo più avanzato sui processi.processo = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE) output, _ = processo.communicate() print(output.decode())
-
English version
Standard and advanced libraries
Python offers a wide range of advanced standard libraries that allow you to perform complex operations easily and efficiently. Here is a detailed overview of the libraries you mentioned:
datetime
: Date and time handling
- What does it do?
- Provides classes to manipulate dates, times and time intervals.
- Main classes:
datetime
: Combines date and time.date
: Handles only date.time
: Handles only time.timedelta
: Represents a duration (difference between two dates or times).
- Examples:
from datetime import datetime, date, timedelta
# Current date and time
current_time = datetime.now()
print(current_time) # Output: 2023-10-25 12:34:56.789012
# Creating a specific date
date = date(2023, 10, 25)
print(date) # Output: 2023-10-25
# Difference between two dates
difference = timedelta(days=5)
new_date = date + difference
print(new_date) # Output: 2023-10-30
collections
: Advanced data types
- What does it do?
- Provides specialized data structures in addition to the built-in ones like lists, tuples, and dictionaries.
- Main structures:
defaultdict
: A dictionary with default values.
from collections import defaultdict
diz = defaultdict(int) # Default values are 0
diz["key"] += 1
print(diz["key"]) # Output: 1
Counter
: Counts occurrences of elements.
from collections import Counter
list = ["a", "b", "a", "c", "b", "a"]
count = Counter(list)
print(count) # Output: Counter({'a': 3, 'b': 2, 'c': 1})
deque
: A double-ended queue.
from collections import deque
coda = deque([1, 2, 3])
coda.append(4) # Append to coda
coda.appendleft(0) # Append to head
print(coda) # Output: deque([0, 1, 2, 3, 4])
itertools
: Advanced iterable operations
- What does it do?
- Provides functions to create and manipulate iterators.
- Main functions:
permutations
: Generates all permutations of an iterable.
from itertools import permutations
perm = permutations([1, 2, 3])
print(list(perm)) # Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), ...]
combinations
: generate all combinations of an iterable.
from itertools import combinations
comb = combinations([1, 2, 3], 2)
print(list(comb)) # Output: [(1, 2), (1, 3), (2, 3)]
cycle
: loop infinitely over an iterable.
from itertools import cycle
cyclic = cycle([1, 2, 3])
for _ in range(5):
print(next(cyclic)) # Output: 1, 2, 3, 1, 2
re
: Regular Expressions
- What does it do?
- Allows you to search, extract, and manipulate text using patterns.
- Main functions:
search
: Searches for a pattern in a string.
import re
text = "Hi, my number is 123-456-7890"
match = re.search(r"\d{3}-\d{3}-\d{4}", text)
if match:
print("Found:", match.group()) # Output: Found: 123-456-7890
findall
: Find all occurrences of a pattern.
numbers = re.findall(r"\d+", text)
print(numbers) # Output: ['123', '456', '7890']
sub
: Replace a pattern with a string.
new_text = re.sub(r"\d{3}-\d{3}-\d{4}", "XXX-XXX-XXXX", text)
print(new_text) # Output: Hello, my number is XXX-XXX-XXXX
os
and shutil
: File and directory management
os
:
- Interacts with the operating system (e.g. file, directory, environment variables management).
- Examples:
import os
# Create a directory
os.mkdir("new_directory")
# List files in a directory
print(os.listdir("."))
# Get the current path
print(os.getcwd())
shutil
:
- Provides high-level operations for managing files and directories (e.g. copy, move).
- Examples:
import shutil
# Copy a file
shutil.copy("file.txt", "copy_file.txt")
# Move a file
shutil.move("file.txt", "new_directory/file.txt")
subprocess
: Running system commands
- What does it do?
- Allows you to run system commands directly from Python.
- Main functions:
run
: Runs a command and captures the output.
import subprocess
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout) # Prints the output of the command
Popen
: Provides more advanced control over processes.
process = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE)
output, _ = process.communicate()
print(output.decode())
Commenti
Posta un commento