探索5个有趣的Python脚本示例

Python是一种功能强大而灵活的编程语言,它提供了各种工具和库,使得编写简洁而有趣的脚本变得轻而易举。无论是图像处理、文件操作、GUI制作还是网络通信,Python都能满足你的需求。下面将介绍五个有趣的Python脚本示例,展示了Python的多才多艺和应用广泛性。

1. 修复模糊老照片

图片[1]-探索5个有趣的Python脚本示例-山海云端论坛

使用PIL(Python Imaging Library)、Matplotlib和Numpy库,我们可以轻松地对模糊的老照片进行修复,恢复图像的清晰度。以下是示例代码:

<code># 导入所需库 import numpy as np import matplotlib.pyplot as plt from PIL import Image import os.path # 读取图片 img_path = "E:\\test.jpg" img = Image.open(img_path) # 图像转化为numpy数组 img = np.asarray(img) flat = img.flatten() # 创建函数:获取直方图 def get_histogram(image, bins): histogram = np.zeros(bins) for pixel in image: histogram[pixel] += 1 return histogram # 执行直方图函数 hist = get_histogram(flat, 256) cs = np.cumsum(hist) nj = (cs - cs.min()) * 255 N = cs.max() - cs.min() cs = nj / N cs = cs.astype('uint8') img_new = cs[flat] img_new = np.reshape(img_new, img.shape) # 显示图像 fig = plt.figure() fig.set_figheight(15) fig.set_figwidth(15) fig.add_subplot(1, 2, 1) plt.imshow(img, cmap='gray') plt.title("Image 'Before' Contrast Adjustment") fig.add_subplot(1, 2, 2) plt.imshow(img_new, cmap='gray') plt.title("Image 'After' Contrast Adjustment") plt.show()</code>

2. 批量压缩文件

使用zipfile库,我们可以编写一个脚本,将指定文件夹中的文件批量压缩成ZIP格式,方便传输和存储。

<code>import os import zipfile from random import randrange def zip_dir(path, zip_handler): for root, dirs, files in os.walk(path): for file in files: zip_handler.write(os.path.join(root, file)) if __name__ == '__main__': to_zip = input("请输入要压缩的文件夹名称:") to_zip = to_zip.strip() + "/" zip_file_name = f'zip{randrange(0,10000)}.zip' zip_file = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) zip_dir(to_zip, zip_file) zip_file.close() print(f'文件已保存为:{zip_file_name}')</code>

3. 创建计算器GUI

使用tkinter库,我们可以创建一个简单的计算器GUI,让用户进行基本的数学运算。

图片[2]-探索5个有趣的Python脚本示例-山海云端论坛
<code>import tkinter as tk root = tk.Tk() root.title("Standard Calculator") root.resizable(0, 0) e = tk.Entry(root, width=35, bg='#f0ffff', fg='black', borderwidth=5, justify='right', font='Calibri 15') e.grid(row=0, column=0, columnspan=3, padx=12, pady=12) # 其余部分略,代码过长</code>

4. PDF转Word

使用pdf2docx库,我们可以将PDF文件转换为Word格式,方便编辑和分享文档内容。

图片[3]-探索5个有趣的Python脚本示例-山海云端论坛
<code>from pdf2docx import Converter import os import sys pdf = input("请输入PDF文件的路径:") assert os.path.exists(pdf), "未找到文件,请检查路径" f = open(pdf,'r+') doc_name_choice = input("是否要给转换后的Word文件命名?(Y/N)") if(doc_name_choice == 'Y' or doc_name_choice == 'y'): doc_name = input("请输入自定义名称:") + ".docx" else: pdf_name = os.path.basename(pdf) doc_name = os.path.splitext(pdf_name)[0] + ".docx" cv = Converter(pdf) path = os.path.dirname(pdf) cv.convert(os.path.join(path, "", doc_name), start=0, end=None) print("Word文件已创建!") cv.close()</code>

5. 自动发送邮件

使用smtplib和email库,我们可以编写一个脚本,实现自动发送邮件的功能,包括文本内容、图片和附件。

图片[4]-探索5个有趣的Python脚本示例-山海云端论坛
<code>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 mail_host = "smtp.163.com" mail_sender = "******@163.com" mail_license = "********" mail_receivers = ["******@qq.com","******@outlook.com"] mm = MIMEMultipart('related') mm["From"] = "sender_name<******@163.com>" mm["To"] = "receiver_1_name<******@qq.com>,receiver_2_name<******@outlook.com>" mm["Subject"] = Header("Python邮件测试", 'utf-8') body_content = """你好,这是一个测试邮件!""" message_text = MIMEText(body_content, "plain", "utf-8") 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) stp = smtplib.SMTP() stp.connect(mail_host, 25) stp.set_debuglevel(1) stp.login(mail_sender, mail_license) stp.sendmail(mail_sender, mail_receivers, mm.as_string()) print("邮件发送成功") stp.quit()</code>

这些示例展示了Python的灵活性和强大功能,你可以根据自己的需求编写各种有趣的脚本,让编程变得更加有趣和具有创造性。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容