31. File Size Analyzer
“`python
import os
from pathlib import Path
def analyze_disk_usage(folder_path, top_n=10):
"""
Analyze the file sizes in a folder and find the largest files
"""
file_sizes = []
for file_path in Path(folder_path).rglob('*'):
if file_path.is_file():
try:
size = file_path.stat().st_size
file_sizes.append((file_path, size))
except OSError:
continue
# Sort by size
file_sizes.sort(key=lambda x: x[1], reverse=True)
print(f"Folder: {folder_path}")
print(f"Total files: {len(file_sizes)}")
print(f"\nTop {top_n} largest files:\n")
for i, (file_path, size) in enumerate(file_sizes[:top_n], 1):
size_mb = size / (1024 * 1024)
print(f"{i:2d}. {file_path.name}")
print(f" Path: {file_path}")
print(f" Size: {size_mb:.2f} MB")
print()
return file_sizes[:top_n]
# Example usage
# analyze_disk_usage("./Downloads", 5)
```
32. Text Encoding Detection and Conversion
“`python
import chardet
def detect_and_convert_encoding(file_path, target_encoding='utf-8'):
"""
Detect the file encoding and convert to the target encoding
"""
# Detect original encoding
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
original_encoding = result['encoding']
confidence = result['confidence']
print(f"File: {file_path}")
print(f"Detected encoding: {original_encoding} (confidence: {confidence:.2%})")
if original_encoding and original_encoding.lower() != target_encoding.lower():
try:
# Read and convert
with open(file_path, 'r', encoding=original_encoding) as f:
content = f.read()
# Backup original file
backup_path = file_path + '.bak'
os.rename(file_path, backup_path)
# Write new encoding
with open(file_path, 'w', encoding=target_encoding) as f:
f.write(content)
print(f"Conversion completed: {original_encoding} -> {target_encoding}")
print(f"Original file backed up as: {backup_path}")
except Exception as e:
print(f"Conversion failed: {str(e)}")
else:
print("No conversion needed")
# Batch conversion
def batch_convert_encoding(folder_path, extensions=['.txt', '.csv'], target_encoding='utf-8'):
"""
Batch convert text file encodings in a folder
"""
for root, dirs, files in os.walk(folder_path):
for file in files:
if any(file.endswith(ext) for ext in extensions):
file_path = os.path.join(root, file)
print(f"\nProcessing file: {file}")
detect_and_convert_encoding(file_path, target_encoding)
# Example usage
# detect_and_convert_encoding("garbled_file.txt")
# batch_convert_encoding("./Documents")
```
33. Simple Calculator
“`python
import math
class SmartCalculator:
"""
Smart calculator that supports common mathematical operations and unit conversions
"""
def __init__(self):
self.history = []
def calculate(self, expression):
"""
Calculate a mathematical expression
"""
try:
# Safely evaluate the expression
allowed_names = {
'abs': abs, 'round': round, 'min': min, 'max': max,
'sqrt': math.sqrt, 'sin': math.sin, 'cos': math.cos,
'tan': math.tan, 'log': math.log, 'log10': math.log10,
'pi': math.pi, 'e': math.e
}
# Replace common symbols
expression = expression.replace('^', '**')
# Calculate
result = eval(expression, {"__builtins__": {}}, allowed_names)
# Record history
self.history.append(f"{expression} = {result}")
return result
except Exception as e:
return f"Calculation error: {str(e)}"
def unit_converter(self, value, from_unit, to_unit):
"""
Unit converter
"""
conversions = {
'length': {
'm_km': 0.001, 'km_m': 1000,
'm_cm': 100, 'cm_m': 0.01,
'inch_cm': 2.54, 'cm_inch': 0.393701,
'feet_m': 0.3048, 'm_feet': 3.28084
},
'weight': {
'kg_g': 1000, 'g_kg': 0.001,
'kg_lb': 2.20462, 'lb_kg': 0.453592,
'oz_g': 28.3495, 'g_oz': 0.035274
},
'temperature': {
'c_f': lambda c: c * 9/5 + 32,
'f_c': lambda f: (f - 32) * 5/9,
'c_k': lambda c: c + 273.15,
'k_c': lambda k: k - 273.15
}
}
# Find conversion factor
for category, rules in conversions.items():
key = f"{from_unit}_{to_unit}"
if key in rules:
factor = rules[key]
if callable(factor):
return factor(value)
else:
return value * factor
return "Unsupported unit conversion"
def show_history(self):
"""
Show calculation history
"""
print("\nCalculation History:")
for i, record in enumerate(self.history[-10:], 1): # Show last 10 records
print(f"{i}. {record}")
# Example usage
calc = SmartCalculator()
# print(calc.calculate("2 + 3 * 4")) # Output: 14
# print(calc.unit_converter(100, 'cm', 'inch')) # Output: 39.3701
# calc.show_history()
```
34. Random Password Generator
“`python
import secrets
import string
def generate_password(length=12, use_uppercase=True, use_numbers=True, use_symbols=True):
"""
Generate a strong random password
"""
characters = string.ascii_lowercase
if use_uppercase:
characters += string.ascii_uppercase
if use_numbers:
characters += string.digits
if use_symbols:
characters += string.punctuation
if not characters:
return "Error: At least one character type must be selected"
# Ensure the password contains various types of characters
password = []
if use_uppercase:
password.append(secrets.choice(string.ascii_uppercase))
if use_numbers:
password.append(secrets.choice(string.digits))
if use_symbols:
password.append(secrets.choice(string.punctuation))
# Fill remaining length
remaining_length = length - len(password)
password.extend(secrets.choice(characters) for _ in range(remaining_length))
# Randomly shuffle
secrets.SystemRandom().shuffle(password)
return ''.join(password)
def password_strength_checker(password):
"""
Check password strength
"""
score = 0
feedback = []
# Length check
if len(password) >= 12:
score += 2
elif len(password) >= 8:
score += 1
else:
feedback.append("Password too short, at least 8 characters recommended")
# Character type check
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_symbol = any(c in string.punctuation for c in password)
char_types = sum([has_upper, has_lower, has_digit, has_symbol])
if char_types >= 4:
score += 2
elif char_types >= 3:
score += 1
else:
feedback.append("Password should include uppercase letters, numbers, and symbols")
# Strength rating
if score >= 3:
strength = "Strong"
elif score >= 2:
strength = "Medium"
else:
strength = "Weak"
return {
'strength': strength,
'score': score,
'feedback': feedback,
'has_upper': has_upper,
'has_lower': has_lower,
'has_digit': has_digit,
'has_symbol': has_symbol
}
# Example usage
# password = generate_password(16, True, True, True)
# print(f"Generated password: {password}")
# strength = password_strength_checker(password)
# print(f"Password strength: {strength['strength']}")
```
35. Simple To-Do List Manager
“`python
import json
from datetime import datetime, timedelta
class TodoManager:
"""
Simple to-do list manager
"""
def __init__(self, data_file="todos.json"):
self.data_file = data_file
self.todos = self.load_todos()
def load_todos(self):
"""Load to-do items"""
try:
with open(self.data_file, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
return []
def save_todos(self):
"""Save to-do items"""
with open(self.data_file, 'w', encoding='utf-8') as f:
json.dump(self.todos, f, ensure_ascii=False, indent=2)
def add_todo(self, task, priority="Medium", due_date=None):
"""Add a to-do item"""
todo = {
'id': len(self.todos) + 1,
'task': task,
'priority': priority,
'due_date': due_date,
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
'completed': False
}
self.todos.append(todo)
self.save_todos()
print(f"Added to-do: {task}")
def list_todos(self, show_completed=False):
"""List to-do items"""
print("\nTo-Do List:")
print("-" * 50)
filtered_todos = [t for t in self.todos if show_completed or not t['completed']]
if not filtered_todos:
print("No to-do items available")
return
for todo in filtered_todos:
status = "✓" if todo['completed'] else "○"
priority_icon = {"High": "🔥", "Medium": "⭐", "Low": "📌"}.get(todo['priority'], "📌")
print(f"{todo['id']:2d}. {status} {priority_icon} {todo['task']}")
if todo['due_date']:
print(f" Due: {todo['due_date']}")
print(f" Created: {todo['created_at']}")
print()
def complete_todo(self, todo_id):
"""Mark as completed"""
for todo in self.todos:
if todo['id'] == todo_id:
todo['completed'] = True
todo['completed_at'] = datetime.now().strftime('%Y-%m-%d %H:%M')
self.save_todos()
print(f"Completed: {todo['task']}")
return
print("To-do item not found")
def delete_todo(self, todo_id):
"""Delete a to-do item"""
self.todos = [t for t in self.todos if t['id'] != todo_id]
self.save_todos()
print("Deleted to-do item")
def get_statistics(self):
"""Get statistics"""
total = len(self.todos)
completed = len([t for t in self.todos if t['completed']])
pending = total - completed
print(f"\nTo-Do Statistics:")
print(f"Total: {total}")
print(f"Completed: {completed}")
print(f"Pending: {pending}")
if total > 0:
completion_rate = (completed / total) * 100
print(f"Completion Rate: {completion_rate:.1f}%")
# Example usage
todo = TodoManager()
# todo.add_todo("Complete project report", "High", "2024-07-20")
# todo.add_todo("Buy office supplies", "Medium")
# todo.list_todos()
# todo.complete_todo(1)
# todo.get_statistics()
```
36. Color Code Converter
“`python
import re
def hex_to_rgb(hex_color):
"""
Convert HEX color code to RGB
"""
hex_color = hex_color.lstrip('#')
if len(hex_color) == 3:
hex_color = ''.join(c * 2 for c in hex_color)
if len(hex_color) != 6:
return "Invalid HEX color code"
try:
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
return (r, g, b)
except ValueError:
return "Invalid HEX color code"
def rgb_to_hex(rgb):
"""
Convert RGB to HEX color code
"""
if len(rgb) != 3 or any(not (0 <= c <= 255) for c in rgb):
return "Invalid RGB value"
return '#{:02x}{:02x}{:02x}'.format(*rgb)
def parse_color_input(color_input):
"""
Parse color input (supports multiple formats)
"""
color_input = color_input.strip().lower()
# HEX format
if color_input.startswith('#'):
return {'type': 'hex', 'value': color_input}
# RGB format
rgb_match = re.match(r'rgb?\((\d+),\s*(\d+),\s*(\d+)\)', color_input)
if rgb_match:
r, g, b = map(int, rgb_match.groups())
return {'type': 'rgb', 'value': (r, g, b)}
# Color names (simple implementation)
color_names = {
'red': (255, 0, 0),
'green': (0, 128, 0),
'blue': (0, 0, 255),
'black': (0, 0, 0),
'white': (255, 255, 255),
'yellow': (255, 255, 0),
'cyan': (0, 255, 255),
'magenta': (255, 0, 255)
}
if color_input in color_names:
return {'type': 'name', 'value': color_names[color_input]}
return None
def color_converter(color_input):
"""
Color code converter
"""
parsed = parse_color_input(color_input)
if not parsed:
return "Unrecognized color format"
print(f"Input color: {color_input}")
if parsed['type'] == 'hex':
rgb = hex_to_rgb(parsed['value'])
if isinstance(rgb, tuple):
print(f"HEX: {parsed['value']}")
print(f"RGB: rgb{rgb}")
return {'hex': parsed['value'], 'rgb': rgb}
elif parsed['type'] in ['rgb', 'name']:
rgb = parsed['value']
hex_color = rgb_to_hex(rgb)
if not hex_color.startswith('Invalid'):
print(f"RGB: rgb{rgb}")
print(f"HEX: {hex_color}")
return {'rgb': rgb, 'hex': hex_color}
return "Conversion failed"
# Example usage
# color_converter("#ff0000") # HEX to RGB
# color_converter("rgb(255, 0, 0)") # RGB to HEX
# color_converter("red") # Color name to code
```
37. Simple Markdown Converter
“`python
import re
class MarkdownConverter:
"""
Simple Markdown to HTML converter
"""
def __init__(self):
self.rules = [
(r'\*\*(.*?)\*\*', r'<strong>\1</strong>'), # Bold
(r'\*(.*?)\*', r'<em>\1</em>'), # Italic
(r'`(.*?)`', r'<code>\1</code>'), # Inline code
(r'!\[(.*?)\]\((.*?)\)', r'<img src="\2" alt="\1">'), # Image
(r'\[(.*?)\]\((.*?)\)', r'<a href="\2">\1</a>'), # Link
]
def convert_headers(self, text):
"""Convert headers"""
for i in range(6, 0, -1):
text = re.sub(
f'^{