Python开发功能实用
Python生活实用代码:让日常更高效的“数字魔法”
Python作为一门简洁且功能强大的编程语言,不仅在专业开发领域备受青睐,在日常生活中也能发挥巨大作用。从文件管理到信息处理,从数据统计到趣味应用,掌握一些实用的Python代码,能帮助我们轻松解决生活中的诸多问题。接下来,就让我们一同探索这些实用的Python代码及其使用方法和应用场景。
一、文件管理类
1. 批量重命名文件
在整理大量文件时,手动重命名效率极低,Python可以快速完成批量重命名操作。
import os
def batch_rename(folder_path, prefix="new_"):
files = os.listdir(folder_path)
for index, file in enumerate(files):
old_file_path = os.path.join(folder_path, file)
if os.path.isfile(old_file_path):
file_extension = os.path.splitext(file)[1]
new_file_name = f"{prefix}{index + 1}{file_extension}"
new_file_path = os.path.join(folder_path, new_file_name)
os.rename(old_file_path, new_file_path)
if __name__ == "__main__":
folder_path = "/your/folder/path" # 替换为实际文件夹路径
batch_rename(folder_path)
使用方法:将 /your/folder/path 替换为需要重命名文件所在的文件夹路径,运行代码即可。默认会在文件名前加上 new_ 前缀,并按顺序编号。如果想修改前缀,可在调用函数时传入新的前缀参数,如 batch_rename(folder_path, prefix="image_") 。
应用场景:例如整理下载的图片、音乐文件,或者为项目中的大量文档统一命名格式,方便管理和查找。
2. 自动清理临时文件
系统和各类软件在运行过程中会产生大量临时文件,占用磁盘空间。使用Python可以自动清理这些无用文件。
import os
import shutil
def clean_temp_files():
temp_folders = [
os.path.join(os.environ.get('USERPROFILE'), 'AppData', 'Local', 'Temp'),
os.path.join(os.environ.get('WINDIR'), 'Temp')
]
for folder in temp_folders:
if os.path.exists(folder):
for root, dirs, files in os.walk(folder):
for file in files:
file_path = os.path.join(root, file)
try:
os.remove(file_path)
except Exception as e:
print(f"无法删除 {file_path}: {e}")
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
shutil.rmtree(dir_path)
except Exception as e:
print(f"无法删除 {dir_path}: {e}")
if __name__ == "__main__":
clean_temp_files()
使用方法:直接运行代码,程序会尝试删除系统和用户的临时文件夹中的文件和空文件夹。
应用场景:定期运行该代码,能帮助释放磁盘空间,保持计算机存储整洁,尤其适用于磁盘空间紧张的用户。
二、信息处理类
1. 提取文本中的邮箱地址
在处理大量文本信息时,快速提取其中的邮箱地址能节省大量时间。
import re
def extract_emails(text):
email_pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
return re.findall(email_pattern, text)
if __name__ == "__main__":
text = "联系我:example@example.com 或者 test.user@company.net"
emails = extract_emails(text)
print(emails)
使用方法:将需要提取邮箱地址的文本传入 extract_emails 函数,函数会返回一个包含所有提取到的邮箱地址的列表。
应用场景:比如从会议记录、客户反馈文档、网页爬取的内容中提取相关人员的邮箱地址,便于后续沟通。
2. 统计文本中单词出现频率
分析文章、书籍中的词汇使用情况,有助于了解文本的核心内容和语言风格。
from collections import Counter
import re
def count_words(text):
words = re.findall(r'\w+', text.lower())
return dict(Counter(words))
if __name__ == "__main__":
text = "This is a sample text. This text is for testing word count."
word_counts = count_words(text)
print(word_counts)
使用方法:将目标文本传入 count_words 函数,函数会返回一个字典,其中键为单词,值为该单词在文本中出现的次数。
应用场景:在语言学习中分析阅读材料的词汇分布,辅助制定学习计划;在文学研究中分析作者的用词习惯等。
三、数据统计类
计算个人月度消费统计
通过Python可以对个人消费记录进行统计分析,了解消费情况。假设消费记录存储在一个CSV文件中,包含日期、消费类别、金额等字段。
import pandas as pd
def analyze_monthly_spending(csv_path):
data = pd.read_csv(csv_path)
data['日期'] = pd.to_datetime(data['日期'])
data.set_index('日期', inplace=True)
monthly_spending = data['金额'].resample('M').sum()
category_spending = data.groupby('消费类别')['金额'].sum()
return monthly_spending, category_spending
if __name__ == "__main__":
csv_path = "spending_record.csv" # 替换为实际文件路径
monthly, category = analyze_monthly_spending(csv_path)
print("每月总消费:\n", monthly)
print("各消费类别总花费:\n", category)
使用方法:将存储消费记录的CSV文件路径传入 analyze_monthly_spending 函数,函数会返回每月总消费和各消费类别总花费的统计结果。
应用场景:帮助个人清晰了解自己的消费模式,合理规划预算,控制不必要的支出。
四、趣味应用类
生成随机密码
在设置各类账户密码时,使用随机密码能提高安全性。
import random
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
if __name__ == "__main__":
password = generate_password()
print("生成的随机密码:", password)
使用方法:直接运行代码,默认生成12位包含字母、数字和特殊字符的随机密码。也可以在调用函数时指定密码长度,如 generate_password(length=16) 。
应用场景:为新注册的账户、加密文件等生成高强度随机密码,增强信息安全保护。
绘制个性二维码
将网址、文本信息等生成二维码,方便分享和存储。
import qrcode
def generate_qr_code(data, file_path="qr_code.png"):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save(file_path)
if __name__ == "__main__":
data = "https://www.example.com" # 替换为需要生成二维码的内容
generate_qr_code(data)
使用方法:将需要编码的信息(如网址、文本等)传入 generate_qr_code 函数,默认会在当前目录下生成名为 qr_code.png 的二维码图片。可以修改 file_path 参数指定保存路径和文件名。
应用场景:在宣传海报、名片上添加二维码,方便他人快速获取信息;将重要文档内容生成二维码,便于存储和分享。