包含编程籽料、学习路线图、爬虫代码、安装包等!【点击领取】
Python 作为一门简单易学且功能强大的编程语言,广泛应用于数据分析、自动化、Web开发、人工智能等领域。本文精选 10个Python实战脚本,涵盖 基础语法、文件操作、网络爬虫、数据分析、自动化办公 等方向,帮助你从入门到精通!
📌 文章目录
Python 环境搭建
10个Python实战脚本
① 计算器
② 文件批量重命名
③ 网页爬取天气数据
④ 自动发送邮件
⑤ Excel数据处理
⑥ 图片转字符画
⑦ 简易Web服务器
⑧ 密码生成器
⑨ 人脸检测
⑩ 股票数据可视化
总结
1. Python 环境搭建
在开始之前,确保你已经安装 Python(推荐 Python 3.8+)和代码编辑器(如 VS Code、PyCharm)。
# 检查Python版本
python --version
2. 10个Python实战脚本
① 计算器
功能:实现加减乘除运算
适用人群:Python 新手
def calculator(a, b, op):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
else:
return "无效运算符"
print(calculator(5, 3, '+')) # 输出:8
② 文件批量重命名
功能:批量修改文件夹内的文件名
适用场景:自动化办公
import os
def batch_rename(folder, prefix):
for i, filename in enumerate(os.listdir(folder)):
new_name = f"{prefix}_{i}.txt"
os.rename(os.path.join(folder, filename), os.path.join(folder, new_name))
batch_rename("C:/my_files", "doc")
③ 网页爬取天气数据
功能:爬取某天气网站的实时数据
依赖库:requests, BeautifulSoup
import requests
from bs4 import BeautifulSoup
url = "https://www.weather.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
temp = soup.find("span", class_="CurrentConditions--tempValue--3KcTQ").text
print(f"当前温度: {temp}")
④ 自动发送邮件
功能:使用 Python 发送邮件
依赖库:smtplib
import smtplib
from email.mime.text import MIMEText
def send_email(to, subject, content):
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = "your_email@example.com"
msg['To'] = to
with smtplib.SMTP("smtp.example.com", 587) as server:
server.login("your_email@example.com", "password")
server.send_message(msg)
send_email("friend@example.com", "Python测试邮件", "这是一封自动发送的邮件!")
⑤ Excel数据处理
功能:读取并修改 Excel 文件
依赖库:openpyxl
from openpyxl import load_workbook
wb = load_workbook("data.xlsx")
sheet = wb.active
sheet["A1"] = "新数据"
wb.save("updated_data.xlsx")
⑥ 图片转字符画
功能:将图片转换为 ASCII 字符画
依赖库:Pillow
from PIL import Image
def image_to_ascii(image_path, output_width=100):
img = Image.open(image_path)
img = img.resize((output_width, int(output_width * img.height / img.width)))
ascii_chars = "@%#*+=-:. "
pixels = img.getdata()
ascii_str = ""
for pixel in pixels:
brightness = sum(pixel) / 3
ascii_str += ascii_chars[int(brightness / 255 * (len(ascii_chars) - 1))]
return ascii_str
print(image_to_ascii("photo.jpg"))
⑦ 简易Web服务器
功能:用 Python 启动本地服务器
依赖库:http.server
python -m http.server 8000
⑧ 密码生成器
功能:生成随机密码
依赖库:random, string
import random
import string
def generate_password(length=12):
chars = string.ascii_letters + string.digits + "!@#$%^&*"
return ''.join(random.choice(chars) for _ in range(length))
print(generate_password())
⑨ 人脸检测
功能:识别图片中的人脸
依赖库:opencv
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
img = cv2.imread("face.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow("Detected Faces", img)
cv2.waitKey(0)
⑩ 股票数据可视化
功能:获取股票数据并绘制趋势图
依赖库:yfinance, matplotlib
import yfinance as yf
import matplotlib.pyplot as plt
data = yf.download("AAPL", start="2023-01-01", end="2023-12-31")
data['Close'].plot()
plt.title("Apple Stock Price 2023")
plt.show()
3. 总结
本文介绍了 10个Python实战脚本,涵盖不同难度和应用场景。建议:
✅ 新手:从计算器、文件操作开始
✅ 进阶:尝试爬虫、自动化、数据分析
✅ 高手:挑战人脸识别、Web开发
最后:
希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!
文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【点击这里领取!】
① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习