Advanced Python Topics: AI & ML Mastery
Dive into advanced Python topics for AI & ML. Learn grid search, data retrieval, and boost your machine learning expertise.
Advanced Python Topics
This document covers a range of advanced topics in Python programming, designed to enhance your understanding and practical application of the language.
ArticlesGrid Search in Python
This topic likely refers to searching or querying data within a structured grid-like format, possibly from a specific service or library named "ArticlesGrid." The implementation would typically involve:
- Data Retrieval: Accessing the data source, which could be an API, a database, or a local file.
- Query Construction: Building search queries based on user-defined criteria (e.g., keywords, filters, date ranges).
- Search Execution: Sending the query to the data source and receiving results.
- Result Processing: Parsing and handling the returned data, potentially displaying it in a structured manner.
Example (Conceptual):
# Assuming an 'ArticlesGridAPI' client is available
from articlesgrid_api import Client
api_client = Client("your_api_key")
# Search for articles related to "machine learning" published after 2023
search_results = api_client.search(
query="machine learning",
published_after="2023-01-01",
fields=["title", "author", "publication_date"]
)
for article in search_results:
print(f"Title: {article['title']}, Author: {article['author']}, Published: {article['publication_date']}")
NSE Tools in Python
This refers to leveraging Python for interacting with tools or data provided by the National Stock Exchange (NSE) of India. This typically involves:
- Data Fetching: Using libraries or APIs to download historical and real-time stock data, company information, and market trends from NSE.
- Data Analysis: Employing Python's data science libraries (Pandas, NumPy) for analyzing stock prices, calculating technical indicators, and identifying patterns.
- Algorithmic Trading: Developing trading strategies and backtesting them using the fetched data.
- Visualization: Creating charts and graphs to visualize market performance and trends.
Key Libraries:
nsepy
: A popular library for fetching NSE data.pandas
: For data manipulation and analysis.matplotlib
/seaborn
: For data visualization.
Example (using nsepy
):
from nsepy import get_history
from datetime import date
import pandas as pd
# Get historical data for Reliance Industries
reliance_data = get_history(symbol='RELIANCE',
start=date(2023, 1, 1),
end=date(2023, 12, 31),
index=False)
print(reliance_data.head())
Python Higher-Order Functions
A higher-order function is a function that either takes other functions as arguments, returns a function, or both. This is a fundamental concept in functional programming and is widely used in Python.
Key Concepts:
- Functions as First-Class Citizens: In Python, functions can be treated like any other variable – assigned to variables, passed as arguments, and returned from other functions.
- Common Higher-Order Functions:
map()
,filter()
,reduce()
(fromfunctools
). - Lambda Functions: Anonymous functions often used with higher-order functions.
Examples:
-
map()
: Applies a function to each item in an iterable.numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x**2, numbers)) print(squared_numbers) # Output: [1, 4, 9, 16, 25]
-
filter()
: Filters items from an iterable based on a function that returnsTrue
orFalse
.numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # Output: [2, 4, 6]
-
functools.reduce()
: Applies a function cumulatively to the items of an iterable, from left to right, so as to reduce the iterable to a single value.from functools import reduce numbers = [1, 2, 3, 4, 5] sum_of_numbers = reduce(lambda x, y: x + y, numbers) print(sum_of_numbers) # Output: 15
Arrays
While Python's built-in list
type is often used like an array, it's a dynamic, heterogeneous collection. For more efficient, numerically focused array operations, especially in scientific computing, the array
module or NumPy arrays are preferred.
-
array
Module: Provides a more memory-efficient way to store sequences of basic C data types (e.g., integers, floats).import array # 'i' specifies signed integer type my_array = array.array('i', [1, 2, 3, 4, 5]) print(my_array) print(my_array[0])
-
NumPy Arrays: The de facto standard for numerical computing in Python, offering powerful N-dimensional array objects and a vast collection of mathematical functions.
import numpy as np my_numpy_array = np.array([1, 2, 3, 4, 5]) print(my_numpy_array) print(my_numpy_array * 2) # Element-wise multiplication
Assert
The assert
statement is a debugging aid that tests a condition. If the condition is False
, an AssertionError
is raised, and the program typically halts. It's useful for checking invariants and preconditions during development.
Syntax:
assert condition, message
condition
: The expression that is evaluated.message
(optional): A string that will be part of theAssertionError
if the condition isFalse
.
Example:
def divide(a, b):
assert b != 0, "Divisor cannot be zero"
return a / b
print(divide(10, 2))
# print(divide(10, 0)) # This would raise an AssertionError
Note: Assertions can be disabled when running Python with the -O
(optimize) flag, so they should not be used for error handling that the program relies on for correct operation.
Command-Line Arguments
Python scripts can receive arguments directly from the command line when they are executed. This allows for dynamic input and control over script behavior without modifying the code itself.
Key Modules:
-
sys
Module: Provides access to command-line arguments viasys.argv
.sys.argv
is a list wheresys.argv[0]
is the script name, and subsequent elements are the arguments.# script_name.py import sys print(f"Script name: {sys.argv[0]}") print(f"Number of arguments: {len(sys.argv) - 1}") print(f"Arguments: {sys.argv[1:]}")
Usage:
python script_name.py arg1 arg2 "argument with spaces"
-
argparse
Module: A more powerful and flexible module for parsing command-line arguments, offering features like argument type checking, help messages, and customizable argument formats.# advanced_script.py import argparse parser = argparse.ArgumentParser(description="A script that takes arguments.") parser.add_argument("input_file", help="Path to the input file") parser.add_argument("-o", "--output", help="Path to the output file", default="output.txt") parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output") args = parser.parse_args() print(f"Input file: {args.input_file}") print(f"Output file: {args.output}") if args.verbose: print("Verbose mode enabled.")
Usage:
python advanced_script.py my_data.csv -o processed.csv -v
Data
This is a broad category that can encompass various aspects of data handling in Python, including:
- Data Structures: Lists, tuples, dictionaries, sets, and their appropriate use cases.
- Data Input/Output: Reading from and writing to files (CSV, JSON, XML, plain text), databases, and APIs.
- Data Cleaning and Preprocessing: Handling missing values, transforming data, removing duplicates.
- Data Analysis and Manipulation: Using libraries like Pandas for tabular data, NumPy for numerical data.
- Data Visualization: Creating charts and graphs using Matplotlib, Seaborn, Plotly.
Core Libraries:
pandas
: For data manipulation and analysis with DataFrames.numpy
: For numerical operations, especially on arrays.csv
: For working with CSV files.json
: For working with JSON data.sqlite3
: For interacting with SQLite databases.
Decorators
Decorators are a powerful and expressive feature in Python that allow you to modify or enhance functions or methods. They are a form of metaprogramming. A decorator is a function that takes another function as an argument, adds some functionality, and then returns another function.
Syntax:
Decorators are applied using the @decorator_name
syntax above the function definition.
How they work:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
Common Use Cases:
- Logging: Recording function calls and their arguments/return values.
- Access Control/Authentication: Checking permissions before executing a function.
- Timing: Measuring the execution time of a function.
- Memoization: Caching function results to improve performance.
Generators
Generators are a simple way to create iterators. They are functions that return an iterator and use the yield
keyword to pause their execution and return values one at a time. This makes them memory-efficient for large datasets as they don't store all values in memory at once.
Key Features:
yield
Keyword: Instead ofreturn
, generators useyield
to produce a sequence of values.- Memory Efficiency: Only one value is generated at a time, saving memory.
- Lazy Evaluation: Values are computed only when requested.
Example:
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
# Create a generator object
counter = count_up_to(5)
# Iterate through the generator
for number in counter:
print(number)
Output:
1
2
3
4
5
Generator expressions are a concise way to create generators:
squares = (x**2 for x in range(1, 6))
print(list(squares)) # Output: [1, 4, 9, 16, 25]
Gmail API in Python
Interacting with the Gmail API in Python allows you to programmatically manage your Gmail account, such as sending emails, reading emails, managing labels, and more. This requires using the Google Client Library for Python and setting up API credentials.
Steps Involved:
- Enable Gmail API: In the Google Cloud Console, enable the Gmail API for your project.
- Create Credentials: Generate OAuth 2.0 Client IDs (for web applications or desktop applications) or Service Accounts.
- Install Google Client Library:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
- Authenticate: Use the generated credentials to authenticate your application.
- Use the API: Call methods provided by the
googleapiclient.discovery
module to interact with Gmail.
Example (Sending an Email - simplified):
# This is a conceptual example and requires full authentication setup.
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import base64
from email.mime.text import MIMEText
# ... (Authentication flow to get 'creds') ...
service = build('gmail', 'v1', credentials=creds)
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def send_message(service, user_id, message):
try:
message = service.users().messages().send(userId=user_id, body=message).execute()
print(f"Message Id: {message['id']}")
return message
except Exception as e:
print(f"An error occurred: {e}")
return None
# Example usage:
# sender_email = 'your_email@gmail.com'
# receiver_email = 'recipient_email@example.com'
# subject = 'Test Email from Python'
# body = 'This is a test email sent using the Gmail API.'
# message_to_send = create_message(sender_email, receiver_email, subject, body)
# send_message(service, 'me', message_to_send)
How to Plot a Google Map using the folium
Package in Python
folium
is a Python library that makes it easy to visualize data on an interactive Leaflet map. You can overlay various data types, including geographical points, lines, and polygons, directly onto a Google Maps-like interface (though Leaflet is the underlying technology).
Steps:
- Install
folium
:pip install folium
- Create a Map Object: Initialize a
folium.Map
object, specifying the location (latitude, longitude) and zoom level. - Add Markers or Overlays: Use methods like
folium.Marker()
,folium.Circle()
,folium.PolyLine()
, etc., to add elements to the map. - Save or Display: Save the map to an HTML file or display it directly in environments like Jupyter notebooks.
Example:
import folium
# Create a map centered on a specific location (e.g., Eiffel Tower)
# Coordinates: Latitude 48.8584, Longitude 2.2945
m = folium.Map(location=[48.8584, 2.2945], zoom_start=15)
# Add a marker for the Eiffel Tower
folium.Marker(
[48.8584, 2.2945],
popup='Eiffel Tower',
icon=folium.Icon(color='red')
).add_to(m)
# Add a circle
folium.Circle(
location=[48.8600, 2.2950],
radius=50,
color='blue',
fill=True,
fill_color='blue',
popup='Near Eiffel Tower'
).add_to(m)
# Save the map to an HTML file
m.save('eiffel_tower_map.html')
# In a Jupyter Notebook, you can simply display 'm'
# m
IDEs (Integrated Development Environments)
An IDE is a software application that provides comprehensive facilities to computer programmers for software development. Python programmers use various IDEs, each with its own set of features and benefits.
Popular Python IDEs:
- PyCharm: A full-featured IDE by JetBrains, known for its intelligent code completion, debugging tools, version control integration, and web development support. Offers both a free Community Edition and a paid Professional Edition.
- VS Code (Visual Studio Code): A lightweight but powerful source-code editor developed by Microsoft. With extensions for Python, it becomes a robust IDE offering debugging, linting, IntelliSense, and more. Highly customizable and popular for its speed and flexibility.
- Spyder: Often favored by scientists and engineers, Spyder is an open-source IDE with a focus on data analysis and scientific computing. It includes features like an interactive console, variable explorer, and IPython integration.
- Jupyter Notebook/Lab: While not a traditional IDE, Jupyter provides an interactive computing environment that allows you to create and share documents containing live code, equations, visualizations, and narrative text. Excellent for exploratory data analysis, prototyping, and teaching.
- IDLE: Python's built-in IDE, suitable for beginners. It's simple and includes a basic editor and debugger.
Choosing an IDE: Depends on project needs, personal preference, and required features (e.g., debugging, web development, data science).
Iterator Tools
Python's itertools
module provides a collection of fast, memory-efficient tools that are useful by themselves or in combination to express complex iteration patterns. These tools often work with iterators and generators.
Key Functions:
count(start=0, step=1)
: Creates an iterator that returns evenly spaced values starting withstart
.cycle(iterable)
: Creates an iterator that repeats the elements ofiterable
indefinitely.repeat(object[, times])
: Creates an iterator that returnsobject
over and over again.combinations(iterable, r)
: Returnsr
-length subsequences of elements from the inputiterable
.permutations(iterable, r=None)
: Returnsr
-length permutations of elements from the inputiterable
.product(*iterables, repeat=1)
: Cartesian product of input iterables.chain(*iterables)
: Treats a sequence of iterables as a single sequence.islice(iterable, stop)
orislice(iterable, start, stop[, step])
: Returns selected elements from the iterable.
Example:
import itertools
# Infinite counter
# for i in itertools.count(10, 2):
# print(i)
# if i > 20:
# break
# Cycle through a list
# colors = ['red', 'green', 'blue']
# for color in itertools.cycle(colors):
# print(color)
# # Add a break condition
# Combinations
letters = ['a', 'b', 'c']
print(list(itertools.combinations(letters, 2))) # Output: [('a', 'b'), ('a', 'c'), ('b', 'c')]
# Chain iterables
list1 = [1, 2]
list2 = ['a', 'b']
print(list(itertools.chain(list1, list2))) # Output: [1, 2, 'a', 'b']
Multiprocessing
The multiprocessing
module in Python allows you to create and manage separate processes, enabling true parallel execution of code. This is particularly useful for CPU-bound tasks where you want to utilize multiple CPU cores.
Key Concepts:
- Processes vs. Threads: Unlike threads (which share the same memory space and are subject to the Global Interpreter Lock - GIL), processes have their own memory space, avoiding GIL limitations for CPU-bound tasks.
Process
Class: Represents a separate process.Pool
Class: Manages a pool of worker processes.- Inter-Process Communication (IPC): Mechanisms like
Queue
andPipe
are used for processes to communicate data.
Example (using Pool
):
import multiprocessing
import time
def square_number(x):
"""Calculates the square of a number and simulates work."""
time.sleep(1) # Simulate some work
return x * x
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# Create a pool of worker processes (e.g., number of CPU cores)
with multiprocessing.Pool(processes=4) as pool:
# Map the function to the input data
results = pool.map(square_number, numbers)
print(f"Original numbers: {numbers}")
print(f"Squared numbers: {results}")
PySpark MLlib
Apache Spark's MLlib is a machine learning library built on top of Apache Spark. It provides a scalable and distributed platform for various machine learning tasks, including classification, regression, clustering, and collaborative filtering.
Key Features:
- Scalability: Designed to handle large datasets by distributing computation across a cluster.
- Common Algorithms: Includes implementations of many standard ML algorithms.
- Feature Engineering: Tools for feature extraction, transformation, selection, and construction.
- Pipelines: For constructing and evaluating ML workflows.
Steps:
- Set up Spark Environment: Install Apache Spark and configure your environment.
- Use PySpark: Write Python code that interacts with Spark.
- Load Data: Load your dataset into a Spark DataFrame.
- Feature Engineering: Transform your data into a format suitable for ML algorithms (e.g., using
VectorAssembler
). - Train Models: Instantiate and train MLlib models (e.g.,
LinearRegression
,LogisticRegression
,KMeans
). - Evaluate Models: Use appropriate evaluation metrics.
Example (Conceptual - Logistic Regression):
# This requires a SparkSession and a dataset loaded into a DataFrame
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.evaluation import BinaryClassificationEvaluator
# Assume 'df' is your Spark DataFrame with features and a 'label' column
# Assemble feature columns into a single vector column
assembler = VectorAssembler(inputCols=["feature1", "feature2", ...], outputCol="features")
df_assembled = assembler.transform(df)
# Split data into training and testing sets
(trainingData, testData) = df_assembled.randomSplit([0.7, 0.3], seed=1234)
# Initialize Logistic Regression model
lr = LogisticRegression(featuresCol="features", labelCol="label")
# Train the model
lrModel = lr.fit(trainingData)
# Make predictions on test data
predictions = lrModel.transform(testData)
# Evaluate the model
evaluator = BinaryClassificationEvaluator(rawPredictionCol="rawPrediction", labelCol="label", metricName="areaUnderROC")
auc = evaluator.evaluate(predictions)
print(f"Area Under ROC: {auc}")
Python Magic Methods (Dunder Methods)
Magic methods, also known as "dunder" (double underscore) methods, are special methods in Python that are called automatically by Python in response to certain operations. They allow you to implement behavior for your classes that integrates with Python's built-in operations and syntax.
Naming Convention: They are typically enclosed in double underscores, e.g., __init__
, __str__
.
Common Magic Methods:
__init__(self, ...)
: Constructor, called when an object is created.__str__(self)
: Returns a user-friendly string representation of the object. Called bystr()
andprint()
.__repr__(self)
: Returns an unambiguous string representation of the object, often useful for debugging. Called byrepr()
.__len__(self)
: Returns the length of the object. Called bylen()
.__getitem__(self, key)
: Implements accessing elements using square brackets (e.g.,obj[key]
).__setitem__(self, key, value)
: Implements assigning values using square brackets (e.g.,obj[key] = value
).__add__(self, other)
: Implements the+
operator.__eq__(self, other)
: Implements the==
operator.
Example:
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f'"{self.title}" by {self.author}'
def __len__(self):
return self.pages
def __eq__(self, other):
if isinstance(other, Book):
return self.title == other.title and self.author == other.author
return False
book1 = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 224)
book2 = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 224)
book3 = Book("Pride and Prejudice", "Jane Austen", 279)
print(book1) # Calls __str__
print(len(book1)) # Calls __len__
print(book1 == book2) # Calls __eq__
print(book1 == book3) # Calls __eq__
Python Stacks and Queues
Stacks and Queues are fundamental abstract data types (ADTs) used in computer science. Python's built-in list
can be used to implement both, though collections.deque
is often preferred for performance reasons.
-
Stack: A Last-In, First-Out (LIFO) data structure.
- Operations:
push(item)
: Add an item to the top.pop()
: Remove and return the top item.peek()
: Return the top item without removing it.
- Implementation using
list
:append()
for push,pop()
for pop. - Implementation using
collections.deque
:append()
for push,pop()
for pop.deque
offers O(1) complexity for both.
from collections import deque stack = deque() stack.append('a') # push stack.append('b') # push print(stack.pop()) # pop, outputs 'b' print(stack.pop()) # pop, outputs 'a'
- Operations:
-
Queue: A First-In, First-Out (FIFO) data structure.
- Operations:
enqueue(item)
: Add an item to the rear.dequeue()
: Remove and return the front item.peek()
: Return the front item without removing it.
- Implementation using
collections.deque
:append()
for enqueue,popleft()
for dequeue.deque
is efficient for queue operations. - Implementation using
list
(less efficient):append()
for enqueue,pop(0)
for dequeue (O(n) complexity).
from collections import deque queue = deque() queue.append('a') # enqueue queue.append('b') # enqueue print(queue.popleft()) # dequeue, outputs 'a' print(queue.popleft()) # dequeue, outputs 'b'
- Operations:
Regex (Regular Expressions)
Regular expressions, or regex, are sequences of characters that define a search pattern. Python's re
module provides support for regular expressions, enabling powerful text searching, matching, and manipulation.
Key Functions in re
module:
re.search(pattern, string)
: Scans throughstring
looking for the first location wherepattern
produces a match. Returns a match object orNone
.re.match(pattern, string)
: Ifpattern
matches at the beginning ofstring
, returns a match object, otherwiseNone
.re.findall(pattern, string)
: Returns all non-overlapping matches ofpattern
instring
, as a list of strings.re.finditer(pattern, string)
: Returns an iterator yielding match objects for all non-overlapping matches.re.sub(pattern, repl, string)
: Returns string obtained by replacing the leftmost non-overlapping occurrences ofpattern
instring
by the replacementrepl
.
Common Regex Metacharacters:
.
: Matches any character (except newline).*
: Matches the previous element zero or more times.+
: Matches the previous element one or more times.?
: Matches the previous element zero or one time.^
: Matches the start of the string.$
: Matches the end of the string.[]
: Defines a character set.()
: Groups expressions.\d
: Matches any digit.\w
: Matches any alphanumeric character and underscore.\s
: Matches any whitespace character.
Example:
import re
text = "The quick brown fox jumps over the lazy dog. The dog barks."
# Find all occurrences of "the" (case-insensitive)
matches = re.findall(r"the", text, re.IGNORECASE)
print(matches) # Output: ['The', 'the', 'the']
# Search for the first occurrence of a word starting with 'f'
match = re.search(r"\bf\w*\b", text)
if match:
print(f"Found: {match.group(0)}") # Output: Found: fox
# Replace all occurrences of "dog" with "cat"
new_text = re.sub(r"dog", "cat", text)
print(new_text)
Sending Email
Python provides robust libraries for composing and sending emails, allowing automation of communication tasks.
Key Libraries:
smtplib
: This module implements the client side of the Simple Mail Transfer Protocol (SMTP), used for sending emails.email.mime
: This package helps in creating email messages, especially for handling different content types (plain text, HTML, attachments).
Steps:
- Create Email Content: Use
MIMEText
for plain text or HTML,MIMEMultipart
for more complex messages with attachments. - Connect to SMTP Server: Establish a connection to your email provider's SMTP server (e.g.,
smtp.gmail.com
for Gmail,smtp.mail.yahoo.com
for Yahoo). - Login: Authenticate with your email account credentials.
- Send Email: Use the
sendmail()
method. - Quit Connection: Close the connection.
Example (Sending a Plain Text Email via Gmail):
import smtplib
from email.mime.text import MIMEText
sender_email = "your_email@gmail.com"
receiver_email = "recipient_email@example.com"
password = "your_app_password" # Use an App Password for Gmail
subject = "Test Email from Python"
body = "This is a test email sent using Python's smtplib."
message = MIMEText(body)
message['Subject'] = subject
message['From'] = sender_email
message['To'] = receiver_email
try:
# Connect to the SMTP server (Gmail's SMTP server)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465) # Use 465 for SSL
server.login(sender_email, password)
# Send the email
server.sendmail(sender_email, receiver_email, message.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
finally:
server.quit()
Note: For Gmail, you'll need to enable "Less secure app access" or preferably generate an "App Password" if you have 2-Factor Authentication enabled.
Web Scraping
Web scraping is the process of extracting data from websites. Python is a popular choice for web scraping due to its rich ecosystem of libraries.
Key Libraries:
requests
: For making HTTP requests to fetch web page content.Beautiful Soup
(bs4): For parsing HTML and XML documents, navigating the parse tree, and extracting data.Scrapy
: A more comprehensive framework for building robust web scraping projects, handling requests, parsing, item pipelines, and more.
Steps (using requests
and Beautiful Soup
):
- Install Libraries:
pip install requests beautifulsoup4
- Fetch Web Page: Use
requests.get(url)
to download the HTML content. - Parse HTML: Create a
BeautifulSoup
object from the HTML content. - Find Elements: Use
BeautifulSoup
methods (e.g.,find()
,find_all()
,select()
) to locate the data you need based on tags, classes, IDs, etc. - Extract Data: Get the text or attributes from the found elements.
Example:
import requests
from bs4 import BeautifulSoup
url = 'http://quotes.toscrape.com/'
try:
# Fetch the web page
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Find all quote elements (each quote is in a div with class 'quote')
quotes = soup.find_all('div', class_='quote')
for quote in quotes:
text = quote.find('span', class_='text').get_text()
author = quote.find('small', class_='author').get_text()
print(f"Quote: {text}")
print(f"Author: {author}\n")
except requests.exceptions.RequestException as e:
print(f"Error fetching URL: {e}")
except Exception as e:
print(f"An error occurred during scraping: {e}")
Quick Sort in Python: Fast AI Sorting Algorithm
Master Quick Sort in Python: a fast, in-place, divide-and-conquer sorting algorithm essential for efficient data processing in AI & ML.
Grid Search in Python: Optimize ML Models with GridSearchCV
Master hyperparameter tuning for machine learning with Python's GridSearchCV. Learn how to efficiently test hyperparameter combinations for optimal model performance.