1. Web Scraping with Requests and BeautifulSoup
To extract data from a website, such as headlines or metadata, you can utilize the requests library for HTTP requests and BeautifulSoup for parsing the HTML structure.
import requests
from bs4 import BeautifulSoup
target_url = 'https://www.example.com'
try:
response = requests.get(target_url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
page_header = soup.find('h1').get_text()
print(f"Page Header: {page_header}")
else:
print("Failed to retrieve page")
except Exception as e:
print(f"An error occurred: {e}")
2. Data Visualization using Matplotlib
Visualizing data sets helps in understanding trends. This example uses matplotlib to generate a bar chart comparing different categories.
import matplotlib.pyplot as plt
labels = ['Product A', 'Product B', 'Product C']
sales_figures = [120, 250, 180]
plt.figure(figsize=(8, 5))
plt.bar(labels, sales_figures, color='teal')
plt.title('Quarterly Sales Performance')
plt.ylabel('Units Sold')
plt.xlabel('Products')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
3. Machine Learning with Scikit-Learn
Building a predictive model is straightforward with libraries like Scikit-Learn. The following snippet demonstrates a linear regression model trained on sample data.
from sklearn.linear_model import LinearRegression
import numpy as np
# Training data: feature matrix X and target vector y
X_features = np.array([[5], [10], [15], [20]])
y_target = np.array([7, 14, 21, 28])
regressor = LinearRegression()
regressor.fit(X_features, y_target)
# Predicting for a new value
prediction = regressor.predict([[12]])
print(f"Predicted Value: {prediction[0]:.2f}")
4. Natural Language Processing (NLP) with NLTK
Tokenization is a fundamental step in NLP. This code uses the NLTK libray to split a sentence into individual words.
import nltk
from nltk.tokenize import word_tokenize
# Ensure the tokenizer is available
nltk.download('punkt', quiet=True)
sample_text = "Natural language processing enables computers to understand text."
tokens = word_tokenize(sample_text)
print("Tokens:", tokens)
5. Image Processing with OpenCV
OpenCV provides robust tools for image manipulation. This example loads an image and applies a Gaussian blur to reduce noise.
import cv2
import numpy as np
# Load an image (replace 'image.jpg' with your file path)
input_image = cv2.imread('image.jpg')
if input_image is not None:
# Apply Gaussian Blur
blurred_image = cv2.GaussianBlur(input_image, (15, 15), 0)
cv2.imshow('Original', input_image)
cv2.imshow('Blurred', blurred_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Image not found.")
6. Network Programming with Sockets
Creating a TCP server allows for network communication. The script below sets up a simple server that echoes back messages received from a client.
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 9999))
server.listen(1)
print("Server started on port 9999...")
conn, addr = server.accept()
print(f"Connection established with {addr}")
with conn:
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
7. Datta Analysis with Pandas
The Pandas library is essential for data manipulation. Here, we create a DataFrame and calculate the average value of a specific column.
import pandas as pd
raw_data = {
'Employee': ['John', 'Sarah', 'Mike'],
'Hours_Worked': [40, 35, 42]
}
df = pd.DataFrame(raw_data)
average_hours = df['Hours_Worked'].mean()
print(f"Average Hours Worked: {average_hours:.2f}")
8. Web Development with Flask
Micro-frameworks like Flask allow for rapid web application development. This code creates a basic server with a dynamic route.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to the Home Page"
@app.route('/user/<username>')
def user_profile(username):
return f"User Profile: {username}"
if __name__ == '__main__':
app.run(debug=True, port=5000)
</username>
9. Task Automation with Schedule
Automating repetitive tasks saves time. This script uses the schedule library to run a function every minute.
import schedule
import time
def automated_task():
print("Executing scheduled backup...")
schedule.every().minute.do(automated_task)
while True:
schedule.run_pending()
time.sleep(1)
10. Game Development with Pygame
Pygame is a popular library for creating multimedia applications. This minimal example initializes a window and draws a circle.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pygame Example")
active = True
while active:
for event in pygame.event.get():
if event.type == pygame.QUIT:
active = False
screen.fill((30, 30, 30))
# Draw a red circle
pygame.draw.circle(screen, (200, 50, 50), (300, 200), 50)
pygame.display.flip()
pygame.quit()
sys.exit()