实用而有趣的python小代码片段合集(持续更新)

本文提供了多个使用Python编写的实用脚本示例,涵盖了图片格式转换、PDF加密解密、获取电脑配置信息、文件压缩解压、Excel工作表合并、CPU温度监控、PDF表格提取、图像素描、截图、拼写检查、伪信息生成、手写文本、电脑关机、打印日历、统计图表绘制、警告框、文本转语音、网络速度测试、图案绘制、PDF转Word、邮件发送、计算机唱歌、二维码生成、词云制作、OCR文字识别、动图生成、桌面提醒、翻译、字符画转换、PDF转图片等自动化任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载收集自网络

1.图片转格式

# 图片格式转换, Jpg转Png

# 方法1
from PIL import Image

img = Image.open('test.jpg')
img.save('test1.png')


# 方法2
from cv2 import imread, imwrite

image = imread("test.jpg", 1)
imwrite("test2.png", image)

2.PDF加密和解密

# PDF加密
import pikepdf

pdf = pikepdf.open("test.pdf")
pdf.save('encrypt.pdf', encryption=pikepdf.Encryption(owner="your_password", user="your_password", R=4))
pdf.close()

# PDF解密
import pikepdf

pdf = pikepdf.open("encrypt.pdf",  password='your_password')
pdf.save("decrypt.pdf")
pdf.close()

3.获取电脑的配置信息

# 获取计算机信息
import wmi


def System_spec():
    Pc = wmi.WMI()
    os_info = Pc.Win32_OperatingSystem()[0]
    processor = Pc.Win32_Processor()[0]
    Gpu = Pc.Win32_VideoController()[0]
    os_name = os_info.Name.encode('utf-8').split(b'|')[0]
    ram = float(os_info.TotalVisibleMemorySize) / 1048576

    print(f'操作系统: {os_name}')
    print(f'CPU: {processor.Name}')
    print(f'内存: {ram} GB')
    print(f'显卡: {Gpu.Name}')

    print("\n计算机信息如上 ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑")


System_spec()

4.解压和压缩文件

# 解压文件
from zipfile import ZipFile

unzip = ZipFile("file.zip", "r")
unzip.extractall("output Folder")

5.Excel工作表合并

import pandas as pd

# 文件名
filename = "test.xlsx"
# 表格数量
T_sheets = 5

df = []
for i in range(1, T_sheets+1):
    sheet_data = pd.read_excel(filename, sheet_name=i, header=None)
    df.append(sheet_data)

# 合并表格
output = "merged.xlsx"
df = pd.concat(df)
df.to_excel(output)

6.获取CPU温度

# 获取CPU温度
from time import sleep
from pyspectator.processor import Cpu
cpu = Cpu(monitoring_latency=1)
with cpu:
    while True:
        print(f'Temp: {cpu.temperature} °C')
        sleep(2)

7.提取PDF表格

# 方法①
import camelot

tables = camelot.read_pdf("tables.pdf")
print(tables)
tables.export("extracted.csv", f="csv", compress=True)

# 方法②, 需要安装Java8
import tabula

tabula.read_pdf("tables.pdf", pages="all")
tabula.convert_into("table.pdf", "output.csv", output_format="csv", pages="all")

8.图片素描

# 图像转换
import cv2

# 读取图片
img = cv2.imread("img.jpg")
# 灰度
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
invert = cv2.bitwise_not(grey)
# 高斯滤波
blur_img = cv2.GaussianBlur(invert, (7, 7), 0)
inverse_blur = cv2.bitwise_not(blur_img)
sketch_img = cv2.divide(grey, inverse_blur, scale=256.0)
# 保存
cv2.imwrite('sketch.jpg', sketch_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

9.截图

# 方法1
from mss import mss
with mss() as screenshot:
    screenshot.shot(output='scr.png')

# 方法2
import PIL.ImageGrab
scr = PIL.ImageGrab.grab()
scr.save("scr.png")

# 方法3
import pyautogui
screenshot = pyautogui.screenshot()
screenshot.save("screenshot.png")  

10.拼写检查

# 拼写检查
# 方法①
import textblob

text = "mussage"
print("original text: " + str(text))

checked = textblob.TextBlob(text)
print("corrected text: " + str(checked.correct()))

# 方法②
import autocorrect
spell = autocorrect.Speller(lang='en')

# 以英语为例
print(spell('cmputr'))
print(spell('watr'))
print(spell('survice'))

11.伪信息生成

from faker import Faker
fake = Faker()
print(fake.name())
print(fake.email())
print(fake.country())
print(fake.profile())   

12.手写文本图像

import pywhatkit
pywhatkit.text_to_handwriting('''Learning Python from the basics is extremely important. Before starting to learn python,understanding a base language like c is a must and some of the oops concepts.Python program has many modulesand packages, which helps with efficient programming.
Understanding these modules and 1proper usage of many syntax and libraries is recommended.
In this article, a few modules and packages are used in the program. 
Python includes tons of libraries and some of them are quiet intresting''')

13.电脑关机

import os
shutdown = input("Do you want to shutdown your computer (yes / no): ")
if shutdown == 'yes':
    os.system("shutdown /s /t 1")
else:
    print('Shutdown is not requested')  

14.打印日历

import calendar
year =int( input("Enter the year of the required calendar "))
month = int( input("Enter the month of the required calendar "))
print(calendar.month(year,month))  

15.画统计饼图

import matplotlib.pyplot as plt
Partition = 'Holidays', 'Eating_Out', 'Shopping', 'Groceries'
sizes = [250, 100, 300, 200]
fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=Partition, autopct='%1.1f%%', shadow=True, startangle=90)         
ax1.axis('equal')
plt.show()

16.弹出告警框

import pyautogui
num=int(input("Enter a value to divide 100"))
if num == 0:
    pyautogui.alert(" Alert!!! 100 cannot be divided by 0")
else:
    print(f'The value is {100/num}')  

17.文本转语音

import pyttsx3
engine = pyttsx3.init()
engine.say('This is a python example in MEDIUM')
engine.runAndWait()      

18.网络监测

import speedtest
speed = speedtest.Speedtest()
download_speed = speed.download()
upload_speed = speed.upload()
print(f'The download speed is {download_speed}')
print(f'The uplaod speed is {upload_speed}') 

19.绘制图案

import random
import turtle
colors = ['red','cyan','pink' ,'yellow', 'green','orange']
t = turtle.Turtle()
t.speed(10)
turtle.bgcolor("black")
length=100
angle =50
size=5
for i in range(length):
    color=random.choice(colors)
    t.pencolor(color)
    t.fillcolor(color)
    t.penup()
    t.forward(i+50)
    t.pendown()
    t.left(angle)
    t.begin_fill()
    t.circle(size)
    t.end_fill()
turtle.exitonclick()
turtle.bgcolor("black")     

20.PDF转换为Word文件

from pdf2docx import Converter
import os 
import sys

# Take PDF's path as input 
pdf = input("Enter the path to your file: ")
assert os.path.exists(pdf), "File not found at, "+str(pdf)
f = open(pdf,'r+')

#Ask for custom name for the word doc
doc_name_choice = input("Do you want to give a custom name to your file ?(Y/N)")

if(doc_name_choice == 'Y' or doc_name_choice == 'y'):
    # User input
    doc_name = input("Enter the custom name : ")+".docx"
    
else:
    # Use the same name as pdf
    # Get the file name from the path provided by the user
    pdf_name = os.path.basename(pdf)
    # Get the name without the extension .pdf
    doc_name =  os.path.splitext(pdf_name)[0] + ".docx"

    
# Convert PDF to Word
cv = Converter(pdf)

#Path to the directory
path = os.path.dirname(pdf)

cv.convert(os.path.join(path, "", doc_name) , start=0, end=None)
print("Word doc created!")
cv.close()

21.发邮件

import smtplib
import email
# 负责构造文本
from email.mime.text import MIMEText
# 负责构造图片
from email.mime.image import MIMEImage
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.header import Header

# SMTP服务器,这里使用163邮箱
mail_host = "smtp.163.com"
# 发件人邮箱
mail_sender = "******@163.com"
# 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程
mail_license = "********"
# 收件人邮箱,可以为多个收件人
mail_receivers = ["******@qq.com","******@outlook.com"]

mm = MIMEMultipart('related')

# 邮件主题
subject_content = """Python邮件测试"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "sender_name<******@163.com>"
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "receiver_1_name<******@qq.com>,receiver_2_name<******@outlook.com>"
# 设置邮件主题
mm["Subject"] = Header(subject_content,'utf-8')

# 邮件正文内容
body_content = """你好,这是一个测试邮件!"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)

# 二进制读取图片
image_data = open('a.jpg','rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
mm.attach(message_image)

# 构造附件
atta = MIMEText(open('sample.xlsx', 'rb').read(), 'base64', 'utf-8')
# 设置附件信息
atta["Content-Disposition"] = 'attachment; filename="sample.xlsx"'
# 添加附件到邮件信息当中去
mm.attach(atta)

# 创建SMTP对象
stp = smtplib.SMTP()
# 设置发件人邮箱的域名和端口,端口地址为25
stp.connect(mail_host, 25)  
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(mail_sender,mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")
# 关闭SMTP对象
stp.quit()

22.让计算机唱歌

import os
def sing():
	os.system("say 'Do Re Mi Fa So La Ti Do'")
sing() # for mac

23.生成二维码

import qrcode

text = input(输入文字或URL:)  
# 设置URL必须添加http://
img =qrcode.make(text)
img.save()                            
#保存图片至本地目录,可以设定路径
img.show()

24.生成词云

import matplotlib.pyplot as plt
from wordcloud import WordCloud
import jieba

text_from_file_with_apath = open('/Users/hecom/23tips.txt').read()

wordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all = True)
wl_space_split =  .join(wordlist_after_jieba)

my_wordcloud = WordCloud().generate(wl_space_split)

plt.imshow(my_wordcloud)
plt.axis(off)
plt.show()

25.识别图片中的文字

import pytesseract
from PIL import Image
img = Image.open('text.jpg')
text = pytesseract.image_to_string(img)
print(text)

26.快速生成动图

import imageio

image_list = ['image/1.jpg','image/2.jpg', 'image/3.jpg', 'image/4.jpg']
gif_name = "dongtu.gif"
duration = 1
frames = []
for image_name in image_list:
    frames.append(imageio.imread(image_name))
imageio.mimsave(gif_name, frames, "GIF", duration=duration)

27.桌面提醒

import win10toast
toaster = win10toast.ToastNotifier()
import schedule
import time
def job():
    toaster.show_toast('提醒', "到吃饭时间了!", duration = 15)
​
schedule.every().hour.do(job)  #scheduling for every hour; you can even change the scheduled time with schedule library
whileTrue:
    schedule.run_pending()
    time.sleep(1)

28.翻译

#import the library 
from translate import Translator
# 指定语言
translator = Translator(to_lang="Hindi")
# 输入要翻译的内容
translation = translator.translate('Hello!!! Welcome to my class')
#输出翻译结果
print(translation)

29.图片转字符画

from PIL import Image
ascii_char = list('"$%_&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-/+@<>i!;:,\^`.')
def get_char(r, b, g, alpha=256):
    if alpha == 0:
        return ' '
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    unit = 256 / len(ascii_char)
    return ascii_char[int(gray//unit)]
def main():
    im = Image.open('astro1.jpg')
    WIDTH, HEIGHT = 100, 40
    im = im.resize((WIDTH, HEIGHT))
    txt = ""
    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j, i)))
        txt += '\n'
    print(txt)
    fo = open("pic_char.txt","w")
    fo.write(txt)
    fo.close()
main()
print("已完成")

30.PDF 转图片

# PDF to Images
# pip install PyMuPDF
import fitz
def pdf_to_images(pdf_file):
    doc = fitz.open(pdf_file)
    for p in doc:
        pix = p.get_pixmap()
        output = f"page{p.number}.png"
        pix.writePNG(output)
pdf_to_images("test.pdf")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值