如果你正在学习Python,那么你需要的话可以,点击这里👉Python重磅福利:入门&进阶全套学习资料、电子书、软件包、项目源码等等免费分享!
一、引言
Python 作为一门功能强大且易于学习的编程语言,能够帮助我们完成各种各样的任务,就像赋予我们超能力一样。在这篇教程中,我们将介绍 20 个实用的 Python 编程脚本,即使你是编程小白,也能轻松理解并运用它们来解决日常问题或提升工作效率。
二、脚本示例
(一)文件整理脚本
import os
import shutil
# 定义源文件夹和目标文件夹
source_folder = "C:/Users/YourName/Downloads"
destination_folder = "C:/Users/YourName/Documents/SortedFiles"
# 获取源文件夹中的所有文件
files = os.listdir(source_folder)
# 遍历文件并根据文件扩展名移动到相应文件夹
for file in files:
file_extension = os.path.splitext(file)[1]
if file_extension:
target_folder = os.path.join(destination_folder, file_extension[1:])
if
not os.path.exists(target_folder):
os.makedirs(target_folder)
shutil.move(os.path.join(source_folder, file), target_folder)
这个脚本可以将指定下载文件夹中的文件按照扩展名分类整理到不同的文件夹中,让你的文件管理井井有条。
(二)图片批量处理脚本
from PIL import Image
# 图片文件夹路径
image_folder = "C:/Images"
# 遍历文件夹中的图片
for image_file in os.listdir(image_folder):
if image_file.endswith(".jpg") or image_file.endswith(".png"):
# 打开图片
image = Image.open(os.path.join(image_folder, image_file))
# 进行一些处理,比如调整大小
new_image = image.resize((800, 600))
# 保存处理后的图片
new_image.save(os.path.join(image_folder, "resized_" + image_file))
它能够批量处理图片,如调整大小,方便你在需要统一图片规格时使用。
(三)文本统计脚本
text = "This is a sample text. Python is great. We can do a lot with Python."
# 统计单词出现次数
word_count = {}
words = text.split()
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 打印统计结果
for word, count in word_count.items():
print(f"{word}: {count}")
可以对一段文本中的单词出现次数进行统计,对于文本分析的初步探索很有帮助。
(四)简单的网络爬虫脚本
import requests
from bs4 import BeautifulSoup
# 目标网页
url = "https://www.example.com"
# 获取网页内容
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取网页中的标题
titles = soup.find_all('h1')
for title in titles:
print(title.text)
这个脚本可以抓取网页中的标题信息,让你能够快速获取网页的关键内容。
(五)密码生成器脚本
import random
import string
# 定义密码长度
password_length = 12
# 生成包含字母、数字和特殊字符的密码
password_characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(password_characters) for i in
range(password_length))
print(password)
帮你生成高强度的密码,保障账户安全。
(六)系统信息获取脚本
import platform
# 获取操作系统信息
print(platform.system())
# 获取计算机名称
print(platform.node())
# 获取处理器信息
print(platform.processor())
可以快速查看计算机的一些基本系统信息。
(七)邮件发送脚本
import smtplib
from email.mime.text import MIMEText
# 发件人邮箱和密码
sender_email = "your_email@example.com"
sender_password = "your_password"
# 收件人邮箱
recipient_email = "recipient@example.com"
# 邮件内容
message = MIMEText("This is a test email sent from Python.")
message['Subject'] = "Test Email"
message['From'] = sender_email
message['To'] = recipient_email
# 发送邮件
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, recipient_email, message.as_string())
允许你在 Python 中发送邮件,实现自动化的邮件通知功能。
(八)数据备份脚本
import shutil
# 源数据文件夹
source_data = "C:/Data"
# 备份文件夹
backup_folder = "C:/Backup/DataBackup"
# 进行数据备份
shutil.copytree(source_data, backup_folder)
确保你的重要数据定期备份,防止数据丢失。
(九)二维码生成器脚本
import pyqrcode
# 要编码的信息
data = "https://www.example.com"
# 生成二维码
qr = pyqrcode.create(data)
# 保存二维码为图片
qr.png('qr_code.png', scale=8)
能够根据给定信息生成二维码,方便分享链接等信息。
(十)音频播放脚本
from playsound import playsound
# 音频文件路径
audio_file = "C:/Music/song.mp3"
# 播放音频
playsound(audio_file)
让你可以在 Python 程序中播放音频文件。
(十一)PDF 合并脚本
from PyPDF2 import PdfFileMerger
# 要合并的 PDF 文件列表
pdf_files = ["file1.pdf", "file2.pdf", "file3.pdf"]
# 创建合并对象
merger = PdfFileMerger()
# 逐个添加 PDF 文件
for pdf_file in pdf_files:
merger.append(pdf_file)
# 保存合并后的 PDF 文件
merger.write("merged.pdf")
merger.close()
将多个 PDF 文件合并成一个,便于文档管理。
(十二)天气查询脚本
import requests
# 天气 API 地址和 API 密钥(需注册获取)
api_url = "https://api.openweathermap.org/data/2.5/weather"
api_key = "your_api_key"
# 城市名称
city = "New York"
# 发送请求获取天气数据
params = {"q": city, "appid": api_key}
response = requests.get(api_url, params=params)
data = response.json()
# 打印天气信息
print(f"Temperature: {data['main']['temp']} K")
print(f"Weather description: {data['weather'][0]['description']}")
查询指定城市的天气信息,方便你提前规划行程。
(十三)单位换算脚本
# 长度单位换算,从厘米转换为英寸
centimeters = 10
inches = centimeters / 2.54
print(f"{centimeters} centimeters is {inches} inches.")
简单的单位换算脚本,可根据需求扩展到其他单位类型。
(十四)文件搜索脚本
import os
# 搜索关键词和文件夹路径
search_keyword = "report"
search_folder = "C:/Documents"
# 遍历文件夹及其子文件夹查找文件
for root, dirs, files in os.walk(search_folder):
for file in files:
if search_keyword in file:
print(os.path.join(root, file))
在指定文件夹中搜索包含特定关键词的文件,快速定位文件。
(十五)数据库连接与查询脚本(以 MySQL 为例)
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="your_database"
)
# 创建游标
mycursor = mydb.cursor()
# 执行查询语句
mycursor.execute("SELECT * FROM your_table")
# 获取结果
results = mycursor.fetchall()
for row in results:
print(row)
# 关闭游标和连接
mycursor.close()
mydb.close()
实现与 MySQL 数据库的连接并进行简单查询操作。
(十六)屏幕截图脚本
import pyscreenshot as ImageGrab
# 截取屏幕
image = ImageGrab.grab()
# 保存截图
image.save("screenshot.png")
快速截取当前屏幕并保存为图片。
(十七)倒计时脚本
import time
# 设置倒计时时间(秒)
countdown_time = 60
while countdown_time > 0:
print(countdown_time)
time.sleep(1)
countdown_time -= 1
print("Time's up!")
创建一个简单的倒计时器,可用于定时任务提醒等。
(十八)批量重命名脚本
import os
# 文件夹路径
folder_path = "C:/Pictures"
# 新文件名前缀
new_prefix = "new_"
# 遍历文件夹中的文件并重命名
for file in os.listdir(folder_path):
file_extension = os.path.splitext(file)[1]
new_file_name = new_prefix + file
os.rename(os.path.join(folder_path, file), os.path.join(folder_path, new_file_name))
批量修改文件夹中文件的名称,提高文件管理效率。
(十九)JSON 数据处理脚本
import json
# JSON 数据字符串
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# 解析 JSON 数据
data = json.loads(json_data)
# 修改数据
data['age'] = 31
# 将修改后的数据转换回 JSON 字符串
new_json_data = json.dumps(data)
print(new_json_data)
对 JSON 格式的数据进行解析、修改和重新生成,在处理 JSON 数据时非常有用。
(二十)图形绘制脚本(使用 matplotlib)
import matplotlib.pyplot as plt
# 数据
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 绘制折线图
plt.plot(x, y)
# 添加标题和坐标轴标签
plt.title("Simple Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# 显示图形
plt.show()
使用 matplotlib 库绘制简单的图形,如折线图、柱状图等,直观展示数据。
三、总结
这 20 个 Python 编程脚本涵盖了文件处理、网络操作、数据处理、自动化任务等多个方面。通过学习和实践这些脚本,你可以逐渐掌握 Python 的基本语法和常用库的使用方法,从而能够根据自己的需求开发出更多功能强大的程序,真正拥有编程“超能力”。不断探索和尝试,你会发现 Python 在解决各种实际问题中的无限潜力,开启你的编程之旅,让 Python 成为你得力的工具助手。
如果你正在学习Python,那么你需要的话可以,点击这里👉Python重磅福利:入门&进阶全套学习资料、电子书、软件包、项目源码等等免费分享!或扫描下方CSDN官方微信二维码获娶Python入门&进阶全套学习资料、电子书、软件包、项目源码